user6630701
user6630701

Reputation:

Javascript form validation

function validateForm() {
    var x = document.forms["myForm"]["fname"].value;
    if (x == null || x == "") {
        alert("Name must be filled out");
        return false;
    }
}

<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>

This code validates an HTML form. I can't understand what onsubmit="return validateForm()" means. How does it prevent the page from completing the form submission? I understand the logic behind the validation,but I do not understand the procedure by which it stops the submission.

Upvotes: 0

Views: 43

Answers (2)

TestCandidate
TestCandidate

Reputation: 166

This is similar to calling a function in any programming language.

When you are calling the validateForm() function, if the return value is true, the submission will continue normally (or any value that is not false).

However, if you return false as in your case of error, the dom will understand not to submit your form as an error has occurred. returning false is a flag to stop the form from submitting.

Upvotes: 1

MartinMouritzen
MartinMouritzen

Reputation: 241

The form only submits if the code inside onsubmit="" doesn't return false. if x is null or an empty string then validateForm returns false, which stops the submit from happening.

Upvotes: 1

Related Questions