Frage

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>
                                                &nbsp;
                                                <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..

War es hilfreich?

Lösung

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})?$"

Andere Tipps

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})?$";

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

Use this method:

public static boolean validateZip( String zip )
{
   return zip.matches( "\\d{5}" );
} 
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top