How to check the phone number field to accept only numbers and a maximum of 12 digits?

I am doing validation for 10 digits of Indian phone numbers (coding below). I accept only numbers. What I can’t understand is how to throw an error so that if the entered number starts with text or special characters, and also does not allow more than 12 digits. Or either trunacte numbers up to 12 digits if the 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.

+4
source share
4 answers

Use this, I set the maximum length to 12 in TextBox and Validator and checked 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> 
+1
source

This regular expression will contain 10, but allow no more than 12:

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

Here is a Regex 101 to prove it.

This will only allow 10 or 12 only , and the 11-digit number will not be executed.

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

Here is a Regex 101 to prove it.

This will allow 1 to 12 digits:

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

You have now set EnableClientScript to false. This means that JavaScript will not be checked on the client side. However, you need to make sure that you call this.Validate() to force a check on the page before trying to check if there is an IsValid validator.

+6
source

try it

1) maximum limit = 12

 ValidationExpression="\d{0,12}" 

2) length required = 12, but not limit

 ValidationExpression="\d{12}" 
+1
source

Try this regex

 ^[0-9]{12}$ 
0
source

Source: https://habr.com/ru/post/1497423/


All Articles