zipcode regular expression validation
Solution 1
The issue is that your regular expression indicates the four digits must exist if you have the dash. Generally that would be okay but since you're using an input mask the dash always exists, even when it's only five digits. Try the following expression.
ValidationExpression="\d{5}-?(\d{4})?$"
Solution 2
You should only use \\
to escape when you're setting it through C# code-behind.
Use this...
ValidationExpression="\d{5}(-\d{4})?$"
If you were setting it through the C# in the background, then you would need \\d
because \d
would be considered to be a control character...
txtcontactZipCode.ValidationExpression = "\\d{5}(-\\d{4})?$";
This is unless you precede the string with @
, in which case it could be done as...
txtcontactZipCode.ValidationExpression = @"\d{5}(-\d{4})?$";
Solution 3
What about :- [0-9]{5}(\-[0-9]{4})?
[0-9]
Any number between 0 and 9,{5}
= only 5 characters; Altarnativly\d
depending on what you find easier to read.( )
- Create a group\-[0-9]{4}
A Dash followed by 4 numbers?
Optional - Zero or One
Developer
Updated on July 05, 2022Comments
-
Developer almost 2 years
I would like to have a regular expression validator for validating zip code. My zip code length varies up to 9 digits. User can enter either 5 or 9. I should valid if he enters 5 digits or 9 digits. Any thing other than that I would like to raise error.
I tried this expression
ValidationExpression="\\d{5}(-\\d{4})?$"
This is my design I am using rad controls
<telerik:RadMaskedTextBox Mask="#####-####" runat="server" ID="txtcontactZipCode" Width="200px" ValidationGroup="contactValidation"> </telerik:RadMaskedTextBox> <asp:RequiredFieldValidator runat="server" ID="rqrdcontactZipCode" ValidationGroup="contactValidation" Display="Dynamic" ForeColor="Red" ControlToValidate="txtcontactZipCode" ErrorMessage="Zip Code is required"></asp:RequiredFieldValidator> <asp:RegularExpressionValidator ID="regexpcontactZipCode" runat="server" ControlToValidate="txtcontactZipCode" ValidationGroup="contactValidation" Display="Dynamic" ForeColor="Red" ErrorMessage="Should be 5 or 9 Digits" ValidationExpression="\\d{5}(-\\d{4})?$"></asp:RegularExpressionValidator>
But I am unable to valid if I enter as follows
11111-____
Can some one help me..
-
Ghost almost 12 yearsThis may not be relevant for your purposes, but if you're ever going to have Canadian contacts, their zip codes follow a different pattern
-
-
Developer almost 12 yearsEven I use this expression I am getting error when I enter 5 digits.. Even i enter 9 digits this is not validating
-
Mike Perrenoud almost 12 years@User I haves fixed the RegEx and it should work for you. Thanks!
-
Thomas.Benz over 7 yearsThis fails to validate input such as "65784-". The last character is "-".