RegularExpressionValidator only checks once - asp.net

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.

Related

RegularExpressionValidator to limit input length and allow empty strings

I'm really bad with regex and was looking at another question almost identical to this but can't get it to work as I need.
I was to use a RegularExpressionValidator that will allow any character up to 255 characters or nothing at all. I tried,
ValidateExpression="^.{255}$"
but it throws an unhanded exception when the textbox that I'm checking is empty.
I've also tried
ValidateExpression="^.{,255}$"
Thank you
Rodney
Did you try ^.{0,255}$? Not sure what exception you are getting though.
EDIT: Also, if struggling with .Net regex, Regex Hero tester is a great help. I know there are other sites, but this one is by far the best, if you ask me.
The proper expression is ^.{0,255}$.
^.{255}$ will only match if there is exactly 255 characters, while ^.{,255}$ will match the literal string "{,255}".
If there are still issues after trying that, can you tell us the exception?
If it throws an HttpRequestValidationException exception, you can use the members of the UnvalidatedRequestValues class.
Mind that "Validation succeeds if the input control is empty" (MSDN). You may add a RequiredFieldValidator field to ensure that the user does not leave a text box blank (if you use the RequiredFieldValidator control inside an UpdatePanel control, make sure that the validator control and the control it is associated with are in the same panel - MSDN):
<asp:textbox id="myTB"
runat="Server">
</asp:textbox>
// ... MAKE SURE YOU DO NOT USE TextMode="Number"!!!
<asp:RequiredFieldValidator
ID="Value1RequiredValidator"
ControlToValidate="myTB"
ErrorMessage="Please enter a number.<br />"
Display="Dynamic"
runat="server"/>
And as for regex, ^.{255}$ means match any character (except newline) exactly 255 times between string start and end. I think it makes sense to allow ^[1-9][0-9]{0,254}$ (for values like '34', '104', etc.).

RegularExpressionValidator 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.

RegEx stops working when placed into ValidationExpression

I have a text box where a user enters their email address. I need to prevent people using certain email addresses, as this is for corporate (B2B) use.
Can anyone help me with the RegEx which would return false if email addresses contain #gmail or #yahoo?
So far I have this (thanks to #Sabuj) #(yahoo|gmail)\. but when placed into a RegularExpressionValidator it doesn't work:
<asp:RegularExpressionValidator ValidationExpression='#(yahoo|gmail)\.' runat="server" ControlToValidate="txt_email" />
Having read MSDN for more info, I've also tried this but it still returns true regardless of the content entered:
<asp:RegularExpressionValidator ValidationExpression='^(#(yahoo|gmail)\.)$' runat="server" ControlToValidate="txt_email" />
Since e-mail addresses have a complex syntax (more complex than most people realise, for instance, they can contain comments [RFC 822 ยง 3.4.3]), I'd suggest not using regex at all for this. Instead, use a "proper" e-mail parser, then ask the parser for the domain part of the address.
Use this:
<asp:RegularExpressionValidator ValidationExpression=".*#(?!(yahoo|gmail)).*" ControlToValidate="txt_email" runat="server" ErrorMessage="Yahoo and Gmail disallowed"></asp:RegularExpressionValidator>
The validation expression property should be set to match the entire string.
But my regex .*#(?!(yahoo|gmail)).* matches the whole email. So it works :)
You don't need ^ or $ since the string is gonna be a single line.
Also don't forget to add type="email" to your txt_email. It will automatically take care of whether it is a valid email or not.
If the error msg appears, then it isn't valid, but if it doesn't appear, then it is absolutely valid.
I've come up with ^.*#(?!(yahoo|gmail)).*$
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" ValidationExpression="^.*#(?!(yahoo|gmail)).*$" runat="server" ControlToValidate="txt_email" Text="No free email accounts allowed" />
This will allow any text to pass the validator that doesn't contain #yahoo or #gmail.
Don't forget to check Page.IsValid in your code behind, and to include an <asp:ValidationSummary runat="server" /> in your .aspx.
You can use this regex to check whether the mentioned emails are containing or not:
#(gmail|yahoo|mailinator|guerrillamail|dispostable)\.

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-])*

asp.net validation when field is not required

I need to set validation on a textbox where the user types in their email address... This is not a required field though so I want to allow the form to be submitted if the textbox contains the default text ("Email address").
I've posted the code i have already to ensure a valid email address is typed.
<asp:RegularExpressionValidator CssClass="errorpopup" Display="Dynamic" ID="regexpEmail"
ValidationGroup="mySubmit" runat="server" ErrorMessage="<strong>Please enter a valid email address.</strong>"
ControlToValidate="tbEmail" ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*"
SetFocusOnError="true" />
Just enclose the entire regex in (?:...)? to make it optional.
But you're not using a very good e-mail validation regex. Aside from the fact that e-mail addresses can never reliably be validated by regular expressions, you could do a little better by using
^(?:[\w.%+-]+#(?:[\w-]+\.)+[A-Za-z]{2,6}\s*|Email address)?$
This will still not catch all valid addresses, and will match some invalid addresses. But short of the RFC 2822 implementation regex which spans about four or five lines of code, this is probably a good compromise.

Resources