Tutorial :Checking if a form field is numeric while using Jquery to get its value



Question:

Basically, I'm doing this:

var phone = $("#phone").val();  

Then I want to check if:

1) Phone contains only numbers

2) Phone contains at least 10 digits

But the problem is, from my experience, using $("something").val() returns it as a string so isNaN() fails. But I don't want use parseInt() either since it will change strings into numbers as well and then isNaN() will always pass.

Thoughts?


Solution:1

You could use a regular expression like this one:

if (phone.match(/^\d{10,}$/)) {      // the input contains at least 10 digits  }  


Solution:2

Like @Andrew said you can use reg ex to do the check like this.

var regExp = new RegExp("^"+pattern+"$","");  return regExp.test(value);  

Place the above in a function and pass the patern into it to make it re-useable.

Replace pattern with the one that matches your requirements. The one from @Andrew looks like it'll work.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »