jQuery validate phone number with with RegEx - javascript

I have a simple ajax form and I'm trying to validate that it
has a value
that value is a 10 digit number
I'm trying to use RegEx to do so. Here is what I have so far.
var reg = new RegExp("/[0-9]{10}/");
$("#call_form").bind("submit", function() {
if ($("#call_number").val().length < 1 && reg.test($("#call_number").val())) {
$("#call_error").show();
return false;
}
});
I know the problem has to do witht he RegExp as if I remove this portion of the code it validates that the box has a value.
EDIT: Here is the final regex I'm using
var regEx = new RegExp("/[0-9]/");
$("#call_form").bind("submit", function() {
if ($("#call_number").val().length != 10 && !$("#call_number").val().match(regEx)) {
$("#call_error").show();
$.fancybox.resize();
return false;
}
});
EDIT 2
Using the suggestions here is what i'm usign which allows spaces and dashes that then get stripped on check
$("#call_form").bind("submit", function() {
var Phone = $("#call_number").val().replace(/\D+/g,'');
if (Phone.length != 10) {
$("#call_error").show();
$.fancybox.resize();
return false;
}
});

Here is what I use - its simple, just posting if someone is searching for the same.
var a = PHONE_FROM_FIELD;
var filter = /^[0-9-+]+$/;
if (filter.test(a)) {
return true;
}
else {
return false;
}
Cheers!

Your regex works fine for me... you could shorten it to just /[0-9]{10}/.
Your problem is here:
$("#call_number").val().length < 1. If the number is 10 characters long, it will never be less than 1, no?
You probably meant something like this:
$("#call_number").val().length === 10

No one has said what was wrong with your original effort - it's the slashes (/). When calling RegExp as a constructor, you don't need the slashes (which are a token to indicate a regular expression litteral), e.g.:
var re = /\w+/i;
is equivalent to:
var re = new RegExp('\\w+','i');
Note that you have to quote backslashes for special characters.
One last thing - allow spaces in the number. You might remove them before testing or storing though. Users find it much easier to read numbers in blocks of 3 or 4 digits, e.g.
1234 871 098 is easier to read than 1234871098.

something like this:
var regEx = /^(\+\d)*\s*(\(\d{3}\)\s*)*\d{3}(-{0,1}|\s{0,1})\d{2}(-{0,1}|\s{0,1})\d{2}$/;
$("#call_form").bind("submit", function() {
var val = $("#call_number").val();
if (!val.match(regEx)) {
$("#call_error").show();
return false;
}
});

function validate_Phone_Number() {
var number = $('field_Id').val();
var filter = /^((\+[1-9]{1,4}[ \-]*)|(\([0-9]{2,3}\)[ \-]*)|([0-9]{2,4})[ \-]*)*?[0-9]{3,4}?[ \-]*[0-9]{3,4}?$/;
if (filter.test(number)) {
return true;
}
else {
return false;
}
}

use same validation with keypress and keyup using jquery , working for me
jquery code
const goodColor = "#0C6";
const badColor = "#FF0000";
const $mobile_validation = $('#mobile_validation');
$('#mobile').on('keyup keypress', function(e) {
if (e.which == 46 || e.which == 45 || e.which < 48 || e.which > 57) {
event.preventDefault();
}
if(this.value.length !=10 ){
$mobile_validation.text("Please enter 10 digit mobile number ");
$mobile_validation.css("color", badColor);
}
if(this.value.length ===10 ){
$mobile_validation.text("Good!");
$mobile_validation.css("color", goodColor);
}
});
html code
<input type="text" id="mobile" class="form-control" name="telephone" maxlength="10">
<span id="mobile_validation"></span>

// check phone number validation
function validatePhoneNumber(number)
{
count=number.length;
if(number[0]!=" " && number[0]!="-" && number[count-1]!=" " && number[count-1]!="-")
{
temp=number.replace(" ", "");
temp=temp.replace("-", "");
if($.isNumeric(temp))
{
if(temp.length>=7 && temp.length<=12)
{
flag=1;
for(i=1;i<count;i++)
{
if(number[i]=="-" || number[i]==" ")
{
if(number[i-1]=="-" || number[i-1]==" " || number[i+1]=="-" || number[i+1]==" ")
{
flag=0;
}
}
}
if(flag==1)
{
valid=1;
}
else
{
valid=0;
}
}
else
{
valid=0;
}
}
else
{
valid=0;
}
}
else
{
valid=0;
}
return valid;
}

Related

regex expression in javascript not working as expected

we are trying to find if the given string is a valid indian mobile number or not
valid indian mobile number
starts with 7 or 8 or 9
followed by 9 same or different numbers
here is my JavaScript for matching it, but unfortunately it returns false even when number is correct
var mobile_number = $('#number').val();
var mobile_regex = new RegExp('/^[789]\d{9}$/');
if(mobile_regex.test(mobile_number) == false) {
console.log("not valid");
} else {
console.log("valid");
}
Your code has two problems. If you're using a RegExp object, you don't need / characters, and the \ character needs to be escaped.
This would work:
var mobile_regex = new RegExp("^[789]\\d{9}");
Alternatively, if you want to use the other format, this would work:
if(!mobile_number.match(/^[789]\d{9}/)) {
console.log("not valid");
} else {
console.log("valid");
}
You can try this
var mobile_number = $('#number').val();
var mobile_regex = new Regex("^[7-9][0-9]{9}$")
if(mobile_regex.test(mobile_number) == false) {
console.log("not valid");
} else {
console.log("valid");
}

validating input if starts with "T" or "TP"

I have an input. I need to validate if the value starts with "T" followed by numbers or "TP" followed by numbers
Accepted values: T12345 or TP12345
My JavaScript code
var ip_value = document.getElementById('PROMASTER_NO_FW').value;
var v_first_char = ip_value.substr(0, 1);
var v_second_char = ip_value.substr(1, 1);
if (v_first_char.toUpperCase() !== 'T') {
alert('It must be start with T');
return false;
} else {
if (v_second_char.toUpperCase !== 'P' && isNaN(Number(v_second_char))) {
alert('error2');
return false;
} else {
return true;
}
}
function myFunction() {
var ip_value = document.getElementById('test').value; //'AB12345';
var v_first_char = ip_value.substr(0, 1);
var v_second_char = ip_value.substr(1, 1);
if (v_first_char.toUpperCase() !== 'T') {
document.getElementById("error").innerHTML = 'It must be start with T';
} else if (v_second_char.toUpperCase() !== 'P' && isNaN(Number(v_second_char))) {
document.getElementById("error").innerHTML = 'error2';
} else {
document.getElementById("error").innerHTML = 'no error';
}
}
It will work on blur <br />
<input type="text" id="test" onblur="myFunction()">
<span id="error">No Error</span>
I think your logic is perfect and should work fine, you just need to change:
v_second_char.toUpperCase
to
v_second_char.toUpperCase()
in last if condition
Final code will be
var ip_value = document.getElementById('PROMASTER_NO_FW').value;
var v_first_char = ip_value.substr(0, 1);
var v_second_char = ip_value.substr(1, 1);
if (v_first_char.toUpperCase() !== 'T') {
alert('It must be start with T');
return false;
} else {
if (v_second_char.toUpperCase() !== 'P' && isNaN(Number(v_second_char))) { //change in this line
alert('error2');
return false;
} else {
return true;
}
}
Or for the short line of code you can use the regular expression as shown in above answers.
You can use regular expression to achieve your scenario.
var reg = new RegExp(/^TP?[0-9]+$/)
if((string).match(reg))
return true
else
return false
The condition in the if statement can also be used to retrieve the match string from the original string provided.
Pattern matching against a regular expression would be the best thing to use here. Assuming you are returning true if and only if ip_value is a 'T' or 'TP' followed by at least one number:
var ip_value = document.getElementById('PROMASTER_NO_FW').value;
var pattern = new RegExp(/^TP?\d+$/);
return pattern.test(ip_value);
/^TP?\d+$/ is the regular expression pattern or regex for short - if you're not familiar with regexes, a good starting point in the context of Javascript is the MDN Regular Expressions Guide.

JavaScript phone number validation using charCodeAt

I'd like to validate a phone number input using JavaScript to allow only number input. I prefer not to use regex, so I wrote a function like this:
function numberTest(){
for(var i=0;i<phone_number.length;i++){
if(phone_number.charCodeAt(i) >= 48 && phone_number.charCodeAt(i) <=57){
return true;
}else{
return false;
}
}
}
However it does not work. Any ideas why?
This doesn't work because it returns true after the first valid character. Neither branch will get past the first character, so you need to only return if you find an invalid character. Otherwise, if you reach the end without finding an invalid characters, you can finally return true.
Something like:
function numberTest(phone_number) {
for (var i = 0; i < phone_number.length; i++) {
if (phone_number.charCodeAt(i) < 48 && phone_number.charCodeAt(i) > 57) {
return false;
}
}
return true;
}
// Test various values
var testData = ["1234", "12ab", "123451234512345", "a1234123", "123123123a"];
var output = document.getElementById("results");
testData.forEach(function(test) {
var next = document.createElement("li");
next.textContent = numberTest(test);
});
<ul id="results"></ul>
The isNaN() (means is not a number) method will give you the reverted result in a simpler way...
var phone_number = "5511112223";
alert(isNaN(phone_number)); //returns false meaning it is a valid number
phone_number = "55aa1g11d12223";
alert(isNaN(phone_number)); //returns true meaning it is not a number

How to make an input to accept only two decimals and have maximum of 10 digits?

How to make an input to accept only two decimals and have maximum of 10 digits?
I use a function that is activated at onkeypress and gets the length of the value inserted in my input. I got to make it to accept max 10 digits, and maximum of 2 decimals, but after I put those 2 decimals, I can't introduce any other number. For example if I have 1234.11, I can't make it to 10234.11.
function onlyNumbers(){
if($('#GoalQuestionValue').val().toString().length>10) return false;
if($('#GoalQuestionValue').val().indexOf('.') != -1 && $('#GoalQuestionValue').val().toString().length-$('#GoalQuestionValue').val().indexOf('.') >2) return false;
}
function onlyNumbers(){
var n = $('#GoalQuestionValue').val().toString().split('.');
if(n[0].length > 8 || n[0].length < 2) return false; else return true;
}
Why not use a regex to validate this requirement:
if($('#GoalQuestionValue').val().toString().match(/[0-9]{8}\.[0-9]{2}/)!=null && $('#GoalQuestionValue').val().toString().length>11)
try keyup and keydown functions instead of onclick or onchange.
I think you have to check in keypress listener for digit input -
$("#GoalQuestionValue").keypress(function (e) {
if (e.keyCode >= 48 && e.keyCode <= 57) {
if (!isValidNumberStr(this.value)) return false;
}
})
Instead of "onclick" try to use events "onchange" or "oninput".
If you are talking about algorithm, I think this is the best one:
function onlyNumbers() {
var myArray = $('#GoalQuestionValue').val().toString().match(/([0-9]*)\.?([0-9]*)?/);
if(myArray[1]) {
if(myArray[1].length > 10)
return false;
if(myArray[2]) {
if( myArray[2].length > 2 )
return false;
if( myArray[1].length + myArray[2].length > 10)
return false;
}
return true;
}
return false;
}

How do I validate a phone number with javascript?

Would someone a little smarter than myself be able to help me with this function? Its purpose is to validate a text input in a form, a phone number field that will only accept 0-9, dash and dot. The HTML calls the function fine.
function validateFeedback() {
var phone = document.getElementById("phone");
var validNumber = "0123456789.-";
for (i = 0; i < phone.length; i++); {
if (validNumber.indexOf(phone.charAt(i)) == -1); {
alert("You have entered an invalid phone number");
return false;
}
}
return true;
}
Thanks so much for any help.
Regular expressions should help ;)
I'm sorry I haven't tried to run this code, but it should be OK.
function validateFeedback(){
var phone = document.getElementById("phone");
var RE = /^[\d\.\-]+$/;
if(!RE.test(phone.value))
{
alert("You have entered an invalid phone number");
return false;
}
return true;
}
try like this:
function validateFeedback()
{
var phone = document.getElementById("phone");
var validNumber = "0123456789.-";
for(i = 0; i < phone.length; i++) {
if(validNumber.indexOf(phone.charAt(i)) == -1) {
alert("You have entered an invalid phone number");
return false;
}
}
return true;
}
there are ; out of place ...
I think you should use a regex to do this. Something link this:
function validateFeedback() {
var phone = document.getElementById("phone").value;
var reg = new RegExp("[0-9 .-]*");
return reg.test(phone);
}
If the text input is in a form, you can reference it more directly using the form id and the element id:
var phone = document.<formId>.phone;
What you want to test is the value of the element, so you need:
var phone = document.<formName>.phone.value;
Since the function is probably called from a submit listener on the form, you can make things more efficient using:
<form onsubmit="return validateFeedback(this);" ...>
It also seems to me that a phone number has only digits, not "-" or "." characters, so you should only test for digits 0-9.
So the function can be like:
function validateFeedback(form) {
var phoneValue = form.phone.value;
// Use a regular expression to validate the value
// is only digits
if (/\D/.test(phoneValue) {
// value contains non-digit characters
// advise user of error then
return false;
}
}
you may want to test that the length is reasonable too, but note that phone numbers in different places are different lengths, depending on the location and use of area or country codes, and whether the number is for a mobile, landline or other.
I would prefer to use regular expressions for something like this.
Please look at my modified version of your function which should work in all major browsers without any framework.
function validateFeedback() {
// Get input
var phone = document.getElementById("phone"),
// Remove whitespaces from input start and end
phone = (phone || '').replace(/^\s+|\s+$/g, ''),
// Defined valid charset as regular expression
validNumber = "/^[0123456789.-]+$/";
// Just in case the input was empty
if (phone.length == 0) {
// This depends on your application - is an empty number also correct?
// If not, just change this to "return false;"
return true;
}
// Test phone string against the regular expression
if (phone.match(validNumber)) {
return true;
}
// Some invalid symbols are used
return false;
}
Try this one
function validateFeedback(value) {
var length = value.length;
chk1="1234567890()-+ ";
for(i=0;i<length;i++) {
ch1=value.charAt(i);
rtn1=chk1.indexOf(ch1);
if(rtn1==-1)
return false;
}
return true;
}
function phonenumber(inputtxt)
{
var phoneno = /^\d{10}$/;
if((inputtxt.value.match(phoneno))
{
return true;
}
else
{
alert("message");
return false;
}
}

Categories

Resources