1

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" />
Community
  • 1
  • 1
nimra asad
  • 179
  • 6
  • 18

3 Answers3

2

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.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • here is your work in js fiddle and It s NOT working and also accepting alphabets https://jsfiddle.net/z5om6ozh/1/ – nimra asad Apr 04 '17 at 13:38
  • You can *type* anything, but not *submit* anything. That is the purpose of the `pattern` attribute. It is a *final, on-submit* input validation. Disallowing the non-numeric input does not have to be done with regex, see my update. – Wiktor Stribiżew Apr 04 '17 at 13:40
  • Okay This makes sense .. I will use this . as the alternate Thanks :) – nimra asad Apr 04 '17 at 13:43
  • If you find my answer working for you, please consider accepting it, and upvoting if my answer proved helpful to you. – Wiktor Stribiżew Apr 04 '17 at 14:07
0

Try validating it in the controller with an attribute like this

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

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();
    }
});