0

I am a beginner in javascript and am not sure what is going wrong in the code below. It doesn't show any alert when a wrong number is entered. Thanks for the help.The html code for the the attribute is

<li><label for="phonenumber">Phone:</label></li>
<li><input type="tel" name="phonenumber" /></li>

Validation code:

function formValidation()  
{  
    var uphone = document.registration.phonenumber;
    {
        if(ValidatePhone(uphone))
    }
    return false;
}

function ValidatePhone(uphone)  
{  
    var phoneformat = /(^\d{3}-\d{3}-\d{4})$/;  
    if(uphone.value.match(phoneformat))  
    {  
        return true;  
    }  
    else  
    {  
        alert('You have entered an invalid phone number!');  
        uphone.focus();  
        return false;  
    }  
}
11684
  • 7,356
  • 12
  • 48
  • 71
ERR
  • 415
  • 2
  • 6
  • 20
  • 3
    Could you please provide your html or the code where `ValidatePhone` is called? –  Oct 30 '16 at 22:27
  • I attached your function to a text input via an `onchange` handler (`document.getElementById("uphone").addEventListener("change", (event) => ValidatePhone(event.target));`) and it seems to work correctly – Tibrogargan Oct 30 '16 at 22:31
  • 1
    DO NOT validate forms like this because in other countries the phone path is different for example in italy is: +39 111-1111111 – paolobasso Oct 30 '16 at 22:34
  • thanks @Tibrogargan. Thats what I have. I am able to validate other elements in the form with the same kind of approach but for the phone number it doesnt show the alert message. – ERR Oct 30 '16 at 22:47
  • @paolo.basso99 am just trying to validate a basic US phone number. i can also use '^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;' i believe – ERR Oct 30 '16 at 22:50
  • 1
    Don't do this: let the browser do it. See this question: http://stackoverflow.com/questions/2813997/is-it-okay-to-use-input-type-tel-now – Stephan Bijzitter Oct 30 '16 at 23:04
  • Open the page in your favourite web browser. Open the debug tools (typically ctrl-F12). Figure out how to show the source code (varies a lot and the user interface is messy, to say the least). Set a breakpoint at row `var phoneformat = /(^\d{3}-\d{3}-\d{4})$/; ` Run your code, step, and inspect variables. Good luck hunting! – LosManos Oct 30 '16 at 23:24

1 Answers1

0

This function is one big syntax error (which would prevent the whole script from running):

function formValidation()  
{  
    var uphone = document.registration.phonenumber;
    {
        if(ValidatePhone(uphone))
    }
    return false;
}

The inner braces in the function don't do anything here and the if statement has no statement (or block, for that matter) following it, so the } directly following it would cause a SyntaxError. Did you simply mean:

function formValidation()  
{  
    var uphone = document.registration.phonenumber;
    ValidatePhone(uphone);
    return false;
}
11684
  • 7,356
  • 12
  • 48
  • 71