简体   繁体   中英

validating html form with javascript

Basically I want to validate this form, I'm trying to do it with document.getElementByid(); but it is not working can anyone help me with this and why it is not going the way that I'm trying.

 <form name="simple" action="POST">

            <label for="name">
                Name:
            </label>
            <input type="text" id="demo" class="form-control" onsubmit="validate();"><br>

            <label for="email">
                E-mail:
            </label>
            <input type="email" id="email" class="form-control"><br>

            <label for="pwd">
                Password:
            </label>
            <input type="password" id="pwd" class="form-control"><br>

            <label for="phone">
                Phone:
            </label>
            <input type="text" id="phone" class="form-control"><br>

            <input type="button" type="submit" value ="Submit" class="form-control" onclick="validate();" >

            <input type="button" type="reset" value ="Reset" class="form-control">

        </form>
        <script>


        function validate()
    {
        var txt = document.getElementById("demo");
        alert(txt);
        if(txt == " " || txt == null)
        {
            alert("Name can't be left blank");
        }

    }
        </script>

In order to get the value of a field, you have to access the .value field of the element, like so: document.getElementById('demo').value .

In order to catch the submit event, you must set the onsubmit function on the form, like so:

document.getElementById("myform").onsubmit = validate;

Inside the validate function, you have to call return false; in case the input is invalid:

if (txt === null || txt.trim() === '') {
    alert("Name can't be left blank");
    return false;
}

Also, if you're doing validation, look into the pattern and required attributes of the input element. All modern browsers will respect the rules you set with these attributes, and you wouldn't have to manually validate it.

https://www.w3schools.com/tags/att_input_pattern.asp https://www.w3schools.com/tags/att_input_required.asp

The @user337554 is correct, I just want to show you another approach, it's valid to say when we are taking care about forms/fields handling.

Using JavaScript in it's traditional form, you can mind in using the form's onsubmit event to trigger the validation and wait it's return to proceed or not with the POST / GET you want.

The DOM node structure enable you to access fields by it's respective names using something like document.form_name.field_name .

In my example I've passed the form itself as parameter to the validation function, so you will handle it as the native DOM form object with all it's features and children.

Hope it helps you in minding about possibilities in your code, I like that because I can make it cleaner and I can use the DOM tree instead of millions getElementByID .

You can run the code below, it works:

 /** * Triggered by the form's onsubmit event */ function validate(form) { console.info("Beginning the validation.."); // Validating the fields by the DOM nodes sequence from form to input names if(form.demo.value == "") { alert("Name can't be left blank"); return false; // Quit the POST } if(form.email.value == "") { alert("E-mail can't be left blank"); return false; // Quit the POST } if(form.pwd.value == "") { alert("Password can't be left blank"); return false; // Quit the POST } if(form.phone.value == "") { alert("Phone can't be left blank"); return false; // Quit the POST } console.info("Finished!"); // Form is OK return true; } 
 <form action="#" name="simple" action="POST" onsubmit="return validate(this)"> <label for="name"> Name: </label> <input type="text" id="demo" name="demo" class="form-control"><br> <label for="email"> E-mail: </label> <input type="email" id="email" name="email" class="form-control"><br> <label for="pwd"> Password: </label> <input type="password" id="pwd" name="pwd" class="form-control"><br> <label for="phone"> Phone: </label> <input type="text" id="phone" name="phone" class="form-control"><br> <!-- IT'S WRONG, YOU HAVE 2 TYPES HERE, USE SUBMIT TO INTERCEPT THE EVENT <input type="button" type="submit" value ="Submit" class="form-control" > --> <input type="submit" value ="Submit" class="form-control" > <input type="button" type="reset" value="Reset" class="form-control"> </form> 

Use this

function validate() {
  txt = document.getElementById("demo");
  alert(txt);
  if(txt.value.trim() == "" || txt.value == null)
  {
      alert("Name can't be left blank");
  }
}

Note: The keyword var is not present before the txt variable. The value fetches the value of the input field with id demo . The trim() function trims the leading/trailing spaces to ensure the input is not just white space character/s.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM