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.

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. I tried to figure out for hours but could not. You found it out in minutes. Hats off for you.
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

1 Comment

Thank You, I will use the email validation as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.