RegularExpressionValidator asp.net - asp.net

I am trying to make sure that user only can input a-z and 0-9 characters.
To do this I have used the RegularExpressionValidator class:
<asp:TextBox ID="input" Text="search" runat="server" OnTextChanged="searchFunc"></asp:TextBox>
<asp:RegularExpressionValidator ID="regExp" runat="server"
ErrorMessage="only a-z or 0-9 allowed"
ControlToValidate="input"
ValidationExpression="^[a-z0-9]+$" />
Though in the code behind I am trying to check if the user entered valid input by using
regExp.IsValid
But this method returns True even if user inputs !&%()
I can't understand what I've done wrong. Is it my regular expression that is wrong?

Call regExp.IsValid only after the validation has been performed otherwise the default value is set to true.
Try calling regExp.Validate() before checking the IsValid property.

Related

ASP.NET "stacked" regular expression field validators

I have 2 ASP.NET regular expression validators:
^\s*[-+.'\w]+#\w+(?:[-.]\w+)*\.(?!co\s*$)\w{2,}\s*$ check whether the email address is valid
#(adres.pl|vp.pl) check if value contains any of these strings
The problem now is:
The strings in bullet 2 above should NOT be allowed, so o email address "john#adres.pl" should not be allowed.
However, the validators are only positive, meaning that they check if they DO contain the structure.
So when someone currently enters "test#test.com", I get "invalid value"
My code below:
<asp:TextBox ID="tbEmail" runat="server" />
<asp:RegularExpressionValidator ControlToValidate="tbEmail" ErrorMessage="emailinvalid" ValidationExpression="^\s*[-+.'\w]+#\w+(?:[-.]\w+)*\.(?!co\s*$)\w{2,}\s*$" ID="rev1" runat="server"/>
<asp:RegularExpressionValidator ControlToValidate="tbEmail" ErrorMessage="not allowed" ValidationExpression="#(adres.pl|vp.pl)" ID="rev2" runat="server"/>
I was initially thinking of combining expressions 1 and 2, but then I wouldn't know which one fails, and don't know which error to display.
What I would expect is:
"35435gd" -> emailinvalid
"john#adres.pl" -> not allowed
"john#gmail.com" -> all validators are ok
Or perhaps validator rev2 should only execute if rev1 does not throw an error, so "stacking" for a lack of a better term, which a: seems cumbersome and b: I wouldn't know how to do it.
How can I solve for this?
UPDATE 1
<asp:RegularExpressionValidator ControlToValidate="tbEmail" ErrorMessage="invalid" ValidationExpression="^\s*[-+.'\w]+#(?!(?:adres|vp)\.pl\b)\w+(?:[-.]\w+)*\.(?!co\s*$)\w{2,}\s*$" ID="RegularExpressionValidator5" runat="server"/>
<asp:RegularExpressionValidator ControlToValidate="tbEmail" ErrorMessage="not allowed" ValidationExpression="#(?!(?:adres|vp)\.pl\b)" ID="RegularExpressionValidator4" runat="server"/>
"gddg" results in "not allowed", whereas I'd expect "invalid".
When I switch the order of these validators, both errors "invalid" and "not allowed" show.
<asp:RegularExpressionValidator ControlToValidate="tbEmail" ErrorMessage="invalid" ValidationExpression="^\s*[-+.'\w]+#(?!(?:adres|vp)\.pl\b)\w+(?:[-.]\w+)*\.(?!co\s*$)\w{2,}\s*$" ID="RegularExpressionValidator5" runat="server"/>
<asp:RegularExpressionValidator ControlToValidate="tbEmail" ErrorMessage="not allowed" ValidationExpression="#(?!(?:adres|vp)\.pl\b)" ID="RegularExpressionValidator4" runat="server"/>
You can use a single pattern and you might write your existing pattern as:
^\s*[-+.'\w]+#(?!(?:adres|vp)\.pl\b)\w+(?:[-.]\w+)*\.(?!co\s*$)\w{2,}\s*$
The part excluding either adres.pl or vp.pl can be written as #(?!(?:adres|vp)\.pl\b) excluding those matches directly after the #.
You could also use #(?!(?:adres|vp)\.pl\s*$) if that is the last part of the email address just like you currently do for this part \.(?!co\s*$)
See a regex demo.
Note that your pattern would allow leading and trailing whitespace chars for the e-mail address.

RegularExpressionValidator only checks once

I have a form in which I would like guests to enter their name, address etc...
On each field I have a RequiredFieldValidator and a RegularExpressionValidator.
For example:
<asp:TextBox ID="mailNameTextBox" runat="server" MaxLength="70" ValidationGroup="mail"></asp:TextBox>
<asp:RegularExpressionValidator ID="mailNameTextBox_RegularExpressionValidator" runat="server" ErrorMessage="Name can only have letters or spaces." ControlToValidate="mailNameTextBox" ValidationExpression="[a-zA-Z' ']" ValidationGroup="mail" Display="Dynamic">*</asp:RegularExpressionValidator>
<asp:RequiredFieldValidator ID="mailNameTextBox_RequiredFieldValidator" runat="server" ErrorMessage="Name field is required." ControlToValidate="mailNameTextBox" ValidationGroup="mail" Display="Dynamic">*</asp:RequiredFieldValidator>
When I enter a name that includes a number (ie. fails the Regex) and "tab" out of the TextBox, the RegexValidator is instantly displayed with a *, and the form fails to submit. But when I go back and remove the number (ie. pass the Regex), the Validator doesn't seem to re-check the input, and the form will forever fail to submit.
Is there a way to always fire the Validation when leaving the box rather than just the first time (besides calling a Validation method upon the TextBox losing focus). I would have thought this would be automatic?
I have spent some time trying to find an answer to this, and I'm not sure how to word my question to "thouroughly research it", so I'm sorry if this is a duplicate.
I did see this one:
ASP.NET: RegularExpressionValidator Doesn't reCheck the input
but it didn't really help in my case.
Your validation expression is this:
[a-zA-Z' ']
Which means: exactly one letter or one apostroph or one space.
You probably want to use something like the following:
[\w\s]*
Which means: any number of letters or whitespaces.

Multiline textbox new line character regularexpressionvalidator issues

I've been trying to validate a multiline textbox. And of course it doesn't work.
<asp:TextBox ID="t_noteTextBox" runat="server" Width="700" Text='<%# Bind("t_note") %>' TextMode="MultiLine" Rows="3" MaxLength="700" />
<asp:RegularExpressionValidator ID="RegularExpressionValidator2" runat="server" ErrorMessage="Special Characters not allowed." ForeColor="Red"
ControlToValidate="t_noteTextBox" ValidationExpression="(?m)([a-z]|[A-Z]|[0-9]|[ ]|[-]|[_]|[.]|[,]|[\r]|[\n])*" Display="Dynamic"></asp:RegularExpressionValidator>
<asp:RegularExpressionValidator runat="server" ID="valInput" ControlToValidate="t_noteTextBox" ValidationExpression="^[\s\S]{0,740}$"
ErrorMessage="Please enter a maximum of 740 characters" Display="Dynamic" ForeColor="Red"></asp:RegularExpressionValidator>
The expression works fine as long as I don't add a carriage return. As soon as I go to a new line i get an error.
I even looked up and found the ?m multiline option.
however that doesn't work either.
Testing the regex in Expresso works well.
(?m)([a-z]|[A-Z]|[0-9]|[ ]|[-]|[_]|[.]|[,]|[\r]|[\n])*
But as soon as I put it on the website it doesn't.
Any ideas?
Multiline mode alters the behavior of the anchors (^ or $), which you aren't using.
Singleline mode causes the dot metacharacter to match everything including linefeeds, but you aren't using the dot that way. Like most metacharacters, the dot loses its special meaning inside a character class, so [.] just matches a literal ..
I suspect your problem is that you're allowing the validation to be done on the client side. That is, you haven't set EnableClientScript to "false". Client-side validation uses JavaScript instead of .NET, and the JavaScript regex flavor doesn't support inline modifiers like (?m) and (?s). But that shouldn't matter to you, since you aren't using the dot as a metacharacter.
This should be all you need:
ValidationExpression="[a-zA-Z0-9_.,\s-]*"
You can simplify this quite a bit.
(?m)([\w., -])*
The multiline flag (?m) only allows the anchors ^ and $ to match before and after linebreaks, as opposed to start and end of string normally, so it's not doing what you want here.
If you use \s instead of matching a space, it will match the newline as well.
([\w.,\s-])*

Validation Expression for asp.net

I need to validate textbox value for a password, on client-side.
I want to use RegularExpressionValidator.
Please provide me, the value for 'VALIDATION EXPRESSION'for following two conditions:-
"Password should contain minimum of 8 characters"
"Password should ahve atleast one non -alphanumeric character"
<asp:RegularExpressionValidator
ID="PasswordFormatValidator"
runat="server" Display="Dynamic"
ErrorMessage="Invalid Password Format"
ValidationExpression="??????????????"
ControlToValidate="txtEmail">Invalid Email Format
</asp:RegularExpressionValidator>
Or shall I use Custom Validator. If so, please provide the expression for the req condition.
Here is lots of information about this asp control which demonstrate about the regular expression and how setup ValidationExpression.
Visit MSDN:RegularExpressionValidator Control
for example:
<asp:RegularExpressionValidator id="RegularExpressionValidator1"
ControlToValidate="TextBox1"
ValidationExpression="\d{5}"
Display="Static"
EnableClientScript="false"
ErrorMessage="Zip code must be 5 numeric digits"
runat="server"/>
check this also for more information:
Use Regular Expressions to Constrain Input in ASP.NET
Password
ValidationExpression="(?!^[0-9]*$)(?!^[a-zA-Z]*$)^([a-zA-Z0-9]"{8,10})$
Validates a strong password. It must be between 8 and 10 characters, contain at least one digit and one alphabetic character, and must not contain special characters.
if you just want to check length must be minimum.(atleast 1) can contain any value. you can replace 1 to check any minimum length of password.
ValidationExpression=".{1,}"

In asp.net, I need to add validator to textbox that forces the input to be numbers

In asp.net, I need to add a validator to a textbox that forces the input to be numbers.
Is this built in?
I have already added a required field validator to the textbox.
You could use a Regex Validator to ensure the text is numeric
I think the regex would be
[0-9]*
e.g.
<asp:TextBox ID="tbxNumbers" runat="server" />
<asp:RegularExpressionValidator ID="revNumericValidator" runat="server"
ValidationExpression="^[0-9]*$" ControlToValidate="tbxNumbers" ErrorMessage="Must be Numeric" />
EDIT:
As the other two posters also pointed out you can also use \d to represent a Numeric Character
<asp:RegularExpressionValidator runat="server"
ControlToValidate="numbersOnlyTextBox"
ErrorMessage="Enter only numeric characters."
ValidationExpression="^\\d+$" />
Use a range validator.
<asp:TextBox ID="MyTextBox" MaxLength="4" Width="75"
Text="0" runat="server"></asp:TextBox>
<asp:RangeValidator ID="MyRangeValidator" Display="Static" Type="Integer"
MaximumValue="9999" MinimumValue="0" EnableClientScript="true"
ControlToValidate="MyTextBox" runat="server" SetFocusOnError="true"
ErrorMessage="Ooops"></asp:RangeValidator>
This permits you to use numbers with decimal places (by using Type="Double" or "Currency"), or other kinds of numbers that Windows recognizes.
Check MSDN for more info on the Range Validator Control.
I think there needs to be more clarification of the requirements here. What kind of numbers are we talking about? Positive integers? Any integer? A number with a decimal place? What about commas in the number (1,000)?
I recommend a RegularExpressionValidator to do your work, but these questions make a difference when it comes to which RegEx you use.
In order to provide a better user experience, another thing to add is an AjaxToolkit FilteredTextBox extender, with a FilterType of either "Custom, Numbers" or just "Numbers". The first choice is for when you want to be able to specify decimal points and negative numbers. In that case you must also specify the ValidChars attribute with something like "-.". This will stop a user from entering characters that are not going to make up a valid number such as -123.45 . Note that it does not stop the user from entering the '-' & '.' in incorrect places e.g. "2-..-3" can still be entered. You will need the validators mentioned in other answers to catch these cases.
<ajaxToolkit:FilteredTextBoxExtender ID="ftbe" runat="server"
TargetControlID="numbersOnlyTextBox"
FilterType="Custom, Numbers"
ValidChars="-." />
Or
<ajaxToolkit:FilteredTextBoxExtender ID="ftbe" runat="server"
TargetControlID="numbersOnlyTextBox"
FilterType="Numbers" />

Resources