Search code examples
asp.netregextelerik-radmaskedtextbox

zipcode regular expression validation


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


Solution

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