Federico klez Culloca
Federico klez Culloca

Reputation: 27119

Javascript phone number validation

I need to validate a phone number in javascript. The requirements are:

they should be 10 digits, no comma, no dashes, just the numbers, and not the 1+ in front

this is what I wrote so far

function validatePhone(field,alerttxt) {
    with (field) {
        if(value.length > 10) {
            alert(alerttext);
            return false;
        }
        for(i = 0; i < value.length; i++) {
            if(parseInt(value[i]) == NaN) {
                alert(alerttxt);
                return false;
            }
        }
        return true;
    }
}
function validateForm(thisform) {
        if (validatePhone(phone,"Invalid phone number")==false) {
            phone.focus();
            return false;
        }

    }
}
  <form action="post.php" method="post" id="contactform" onsubmit="return validateForm(this)">
    <ol>
        <label for="phone">Your phone <span class="red"></span></label>
        <input id="phone" name="phone" class="text" />
      </li>
    </ol>
  </form>

but, obviously it doesn't work. How can I write the validatePhone() function so that it works?

Upvotes: 13

Views: 91228

Answers (7)

Geoff Langenderfer
Geoff Langenderfer

Reputation: 946

checkout joi: https://github.com/Salesflare/joi-phone-number

const myCustomJoi = Joi.extend(require('joi-phone-number'));

myCustomJoi.string().phoneNumber().validate('+32494567324');

// The phone number can be transformed to a custom format
// Note that this follows Joi's `convert` option
myCustomJoi.string().phoneNumber({ defaultCountry: 'BE', format: 'e164' }).validate('494322456'); // '+32494322456'
myCustomJoi.string().phoneNumber({ defaultCountry: 'BE', format: 'international' }).validate('494322456'); // '+32 494 32 24 56'
myCustomJoi.string().phoneNumber({ defaultCountry: 'BE', format: 'national' }).validate('494322456'); // '0494 32 24 56'
myCustomJoi.string().phoneNumber({ defaultCountry: 'BE', format: 'rfc3966' }).validate('494322456'); // 'tel:+32-494-32-24-56'
myCustomJoi.string().phoneNumber({ defaultCountry: 'US', strict: true }).validate('7777777777'); // validation error
myCustomJoi.string().phoneNumber({ defaultCountry: 'US'}).validate('7777777777'); // 7777777777

Upvotes: 0

Himabindu
Himabindu

Reputation: 684

Add the pattern in which format you want directly in input tag.

<input id="phone" name="phone" pattern="\d{10}" class="text" />

Upvotes: 0

arnep
arnep

Reputation: 6241

You could use Regular Expressions:

function validatePhone(field, alerttext) {
    if (field.match(/^\d{10}/)) {
         return true;
    } 
    alert(alerttext);
    return false;
}

Upvotes: 7

Aaron Gray
Aaron Gray

Reputation: 11703

Google's libphonenumber is very helpful for validation and formatting of phone numbers all over the world. It is easier, less cryptic, and more robust than using a RegEx, and it comes in JavaScript, Ruby, Python, C#, PHP, and Objective-C flavors.

Upvotes: 11

Peter Brooks
Peter Brooks

Reputation: 49

Code to except only numbers braces and dashes

function DoValidatePhone() {
    var frm = document.forms['editMemberForm'];                
    var stripped = frm.contact.value;
    var isGoodMatch = stripped.match(/^[0-9\s(-)]*$/);
    if (!isGoodMatch) {
        alert("The Emergency Contact number contains invalid characters." + stripped);
        return false;
    }
}

Upvotes: 1

Erik
Erik

Reputation: 20712

phone = phone.replace(/[^0-9]/g, '');
if(phone.length != 10) { 
   alert("not 10 digits");
} else {
  alert("yep, its 10 digits");
} 

This will validate and/or correct based on your requirements, removing all non-digits.

Upvotes: 30

antyrat
antyrat

Reputation: 27765

Fixed function:

function validateForm(thisform) {
        if (validatePhone(thisform.phone,"Invalid phone number")==false) {
            thisform.phone.focus();
            return false;
        }
        return true;
}

Upvotes: 0

Related Questions