Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Validate Phone Number Field to accept only numbers and maximum 12 digits?

I am doing validation for 10 digit Indian phone numbers (coding below). I am accepting digits only. What I can't seem to figure out is how to throw an error so that if the number entered begins with text or special characters and also not allow more than 12 Digits. Or either trunacte numbers to 12 digits if user enters more than 12 digits.

<asp:RegularExpressionValidator ID="phoneregularExpression" runat="server" ErrorMessage="MoreThan10" EnableClientScript="false"
ControlToValidate="txtphone" Display="Static" Text="Please enter atleast 10 digits" ValidationExpression="^([0-9\(\)\/\+ \-]*)$"></asp:RegularExpressionValidator>

Thanks In Advance.

like image 667
Yasmeen Ansari Avatar asked Feb 15 '23 13:02

Yasmeen Ansari


2 Answers

This Regex will make sure there is 10, but allow not more than 12:

^([0-9]{10,12})$

Here is a Regex 101 to prove it.

This one will allow 10 or 12 only, and an 11 digit one will fail.

^([0-9]{10}|[0-9]{12})$

Here is a Regex 101 to prove it.

This one will allow 1 to 12 digits:

^([0-9]{1,12})$

Now, you've set EnableClientScript to false here. Which means there won't be any JavaScript validating it client-side. However, you need to make sure you call this.Validate() to force validation on the page before attempting to check if the validator IsValid.

like image 137
Mike Perrenoud Avatar answered Feb 18 '23 02:02

Mike Perrenoud


Use this i set max length to 12 to TextBox and Validator and validated it on regularexpression and tried it

<asp:TextBox runat="server" ID="txt" MaxLength="12"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" 
        ErrorMessage="Error" ForeColor="Red" ControlToValidate="txt"
        ValidationExpression="^[0-9]{12}$"></asp:RegularExpressionValidator>
like image 44
Ahmed Alaa El-Din Avatar answered Feb 18 '23 03:02

Ahmed Alaa El-Din