1

Friends,

I am trying to validate my html form using an external javascript but I am getting an error. Here are the code details:

<html>
    <head>
        <title>Contact US</title>
        <link href="StyleSheet.css" rel="Stylesheet" type="text/css" />
        <script type = "text/javascript" src = "JavaScript.js"> </script>
    </head>
    <body>
    <h1>Contact Us</h1>
    <form id = "contactUs" action="Index.htm"  onsubmit = "return validateFirstName()">
    <div class="row">
                <span class = "label" >First Name:</span>
                <span class = "formw"><input type="text" name = "fname"/> </span>
     <span class = "formw"><input type="submit"  name = "btnSubmit" value = "Submit" /> </span>
    </div>
</form>
</body>
</html>

My external javascript file "JavaScript.js" contains the following code:

  function validateFirstName() {
        var x = document.forms["contactUs"]["fname"].value;
        if (x == null || x == "") {
            alert("First name cannot be left blank.");
            return false;
        }
        else {
            return true;
        }

but when I clicked the Submit button then I get the following error:

Line: 19 Error: 'validateFirstName' is undefined

Thank You for your help in advance.

niceApp
  • 2,913
  • 8
  • 35
  • 36

2 Answers2

3

You need a closing curly brace on your function.

function validateFirstName() {
    var x = document.forms["contactUs"]["fname"].value;
    if (x == null || x == "") {
        alert("First name cannot be left blank.");
        return false;
    }
    else {
        return true;
    }
} // <- here
Will
  • 19,661
  • 7
  • 47
  • 48
2

Heres my code I had wrote for checking if email inserted is valid. You can customize it to your needs, might be usefull :)

  function readdata()
  {
        a=document.getElementById('email')
        k=a.value
        //document.write(k)
alert(k);
        }

    function emailValidation(elem, helperMsg) {
            var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
            if(elem.value.match(emailExp)){
                            return true;
                            }
                            else{
                            alert(helperMsg);
                            elem.focus();
                            return false;
                            }
    }

Also looking at your code, you lack for curly brace at the end of your JavaScript