2

I am trying to test my form for validation. I don't have an .asp or .php file so I was informed I could use action="". My code doesn't seem to function right.On codepen it shows as values being posted. Jsfiddle gives me an error thats a paragraph long. In browser the page just seems to refresh. I have no alerts showing for anything....

what am I doing wrong here?

HTML:

<form name="name_form" action="" onsubmit="ValidateFormJS()" method="post">
    First Name:
    <input type="text" name="first_name">
    <br> Last Name:
    <input type="text" name="last_name">
    <br>
    <input type="submit" value="Submit">
</form>

Javascript:

function ValidateFormJS() {
    var first = document.forms["name_form"]["first_name"].value;
    var last = document.form["name_form"]["last_name"].value;

    if (first == null || first == "") {
        alert("First name must be filled out.");
        return false;
    } else if (last == null || last == "") {
        alert("Last name must be filled out.");
        return false;
    } else {
        alert("Form Submitted.");
        return true;
    }
}
0

2 Answers 2

3

The returned values from the function are never used. You forgot return before the function call on onsubmit event.

onsubmit="return ValidateFormJS()"

Another problem is that you're using document.form to get the value of last name. It should be document.forms.

The last else can be removed.

Demo

var form = document.forms["name_form"];

function ValidateFormJS() {
  var first = form["first_name"].value,
    last = form["last_name"].value;

  if (first == null || first == "") {
    alert("First name must be filled out.");
    return false;
  } else if (last == null || last == "") {
    alert("Last name must be filled out.");
    return false;
  }
}
<form name="name_form" action="" onsubmit="return ValidateFormJS()" method="post">
  First Name:
  <input type="text" name="first_name">
  <br>Last Name:
  <input type="text" name="last_name">
  <br>
  <input type="submit" value="Submit">
</form>

Sign up to request clarification or add additional context in comments.

Comments

0

try this

in view

<form name="name_form" action="" onsubmit="return ValidateFormJS();" method="post">

in js code

function ValidateFormJS() {
    var first = document.forms["name_form"]["first_name"].value;
    var last = document.form["name_form"]["last_name"].value;

    if (first == null || first == "") {
        alert("First name must be filled out.");
        return false;
    } else if (last == null || last == "") {
        alert("Last name must be filled out.");
        return false;
    }

    alert("Form Submitted.");
    return true;
}

Comments

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.