user3472810 user3472810 - 2 years ago 69
Javascript Question

Optimizing JavaScript Code

I have written the following JS, and it gets the job done, but I have been having a ton of trouble eliminating the repeating code. I keep breaking the functionality.

It's just field validation using a

, and adding an error message below the appropriate field if the input doesn't match the
. It's works, but but I really want to begin writing more succinct code.

If someone can help me do this, I can compare mine and yours and start understanding how to approach this type of task.



Here's my JSFiddle code:

Answer Source

You can reuse the same function for all the 2 validations. The only difference between the 3 functions is that you are trying to append to a different id.

Use this instead of referring to the element specifically, since the input is anyways bound to the element you are looking for.

phone.addEventListener('keyup', validatePhone);
phone2.addEventListener('keyup', validatePhone);
phone3.addEventListener('keyup', validatePhone);

function validatePhone(evt) {    
    var pattern = /^(\(\d{1,2}\)\s)?\(?\d{4}\-\)?[\s.-]?\d{4}$/; //set the regular expression
    var str = this.value; //get the user's input
    var phoneVal = document.getElementById("phoneVal");
    if (phoneVal) { //if the error message div is already on the page
        phoneVal.parentNode.removeChild(phoneVal); //remove it, to prevent a series of error message divs from accumulating
    if (str === "") {//if there is no user input
        phoneVal.parentNode.removeChild(phoneVal);//remove the error message
    if (pattern.test(str) === false) { //if the string doesn't match the expression            
        var elem = document.createElement("div"); //create a DIV
        elem.setAttribute("id", "phoneVal"); //give it an 1)id, 2)class and 3)message
        elem.setAttribute("class", "form-error-msg");   
        if(window.location.href.indexOf("/en") > -1) {
            elem.innerHTML = 'Please enter a valid telephone number.'; 
            elem.innerHTML = 'Por favor introduce un número de teléfono válido.'; 
        this.parentNode.appendChild(elem); //add the div with the current error message
} //end function
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download