Home > Blockchain >  phone number validator js
phone number validator js

Time:09-13

How Can i allow the function to modify and print the number only if it is of the following format: XX-XXXX-XXXX ? This is the code that allows invalid phone numbers like simple text

function updatePhone() {
    var phoneNumbers = "";
    var additionalPhoneNumber = $('#phoneInputAdditional').val()   ",";
    $('.phoneInput').each(function () {
        if ($(this).val() != "")
            phoneNumbers = phoneNumbers   $(this).val().toString()   ",";
        console.log($(this).val());
    });
    if (additionalPhoneNumber != ",")
        phoneNumbers = phoneNumbers   additionalPhoneNumber;

    phoneNumbers = phoneNumbers.substring(0, phoneNumbers.length - 1);

    $.ajax({
        type: "POST",
        url: "/updatePhone",
        data: {"phoneNumbers": phoneNumbers},
        dataType: "json"
    })
        .done(function (response) {
            $("#userPhone").text('Phone: '   response[0]);
            $("#phoneul").empty();
            for (var i = 1; i < response.length; i  )
                $("#phoneul").append('<li class = "col-sm-4 phoneli"> <b>Update Number:</b> <input type = "text" value ="'   response[i]   '" class= "form-control phoneInput"/></li>')
            $("#phoneul").append('<li ><b>Additional Number:</b> <input type = "text" placeholder = "Another Phone Number"  id= "phoneInputAdditional"/></li>')
            $("#good3").show();
                setTimeout(function(){ $("#good3").hide(); }, 800);
        })
        .fail(function () {
            $("#bad3").show();
        });
}

CodePudding user response:

I thought of sth like this:

if ( $(this).val().test(/^\ ?([0-9]{2})\)?[-. ]?([0-9]{4})[-. ]?([0-9]{4})$/) )
            phoneNumbers = phoneNumbers   $(this).val().toString()   ",";
        console.log($(this).val());

CodePudding user response:

You can check out the Regex Library of regex101. There you can find a lot of phone number validators. The one with the most upvotes is for phone and fax numbers for all over the world and was created by Aditya Joshi. It can be found here: https://regex101.com/r/wZ4uU6/1, including an example and a debugger. It is the following:

\ ?\d{1,4}?[-.\s]?\(?\d{1,3}?\)?[-.\s]?\d{1,4}[-.\s]?\d{1,4}[-.\s]?\d{1,9}

The corresponding example:

const regex = /\ ?\d{1,4}?[-.\s]?\(?\d{1,3}?\)?[-.\s]?\d{1,4}[-.\s]?\d{1,4}[-.\s]?\d{1,9}/g;

// Alternative syntax using RegExp constructor
// const regex = new RegExp('\\ ?\\d{1,4}?[-.\\s]?\\(?\\d{1,3}?\\)?[-.\\s]?\\d{1,4}[-.\\s]?\\d{1,4}[-.\\s]?\\d{1,9}', 'g')

const str = ` 49 172 7470791 
 49 621 60-6641516 
 49 621 60-41516 
8-1-6641516 
61 41516 
6641516 
41516 `;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex  ;
    }
    
    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}

  • Related