nimra asad
nimra asad

Reputation: 179

How to restrict number field with 10 digits only

I am trying to create a text field where One can type his/her mobile numbers 10 digits only. NO spacing dash coma or alphabets. I tried using the following regex from the given link but it is not working. I am using chrome and even tried on fiddler. I took reference from this code.

 <input type="number" pattern="^[0-9]{1,10}$" title="adc" />

Upvotes: 1

Views: 7676

Answers (3)

beshoy ekram
beshoy ekram

Reputation: 1

use the following attr on controller :-

[RegularExpression("[0-9]{10}", ErrorMessage = "Enter Valid number")]

Or: 1- make input field's type is number

2- type the following Js

$('#idInputTxt').keypress(function (e) {

  if (this.value.length == 10|| (e.which > 57 && e.which < 65) || 
     (e.which > 90 && e.which < 97) ||  (e.which > 122) ||(e.which < 48 || e.which > 57))
    {
        e.preventDefault();
    }
});

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627609

You need to use type="text" and then use \d{10} regex. Note that a regex validation does not work when your <input> type is number. Also, the regex inside the pattern attribute is anchored by default, that is why you do not need the anchors (^ for the start of string and $ for the end of string). The pattern="\d{10}" regex will be translated into /^(?:\d{10})$/ pattern that matches a string consisting of exactly 10 digits.

input:valid {
  color: navy;
}
input:invalid {
  color: red;
}
<form name="form1"> 
 <input type="text" pattern="\d{10}" title="Error: 10 digits are required." onkeypress="return (event.charCode == 8 || event.charCode == 0) ? null : event.charCode &gt;= 48 && event.charCode &lt;= 57"  />
 <input type="Submit"/> 
</form>

To disallow a non-numeric input, add onkeypress="return (event.charCode == 8 || event.charCode == 0) ? null : event.charCode >= 48 && event.charCode <= 57" to the <input> element.

Upvotes: 2

Try validating it in the controller with an attribute like this

[RegularExpression("[0-9]{10}", ErrorMessage = "Please enter valid Number")]

Upvotes: 0

Related Questions