Processing and Validating Forms

HTML5 Validation

Semantic Types

Pattern validation

required
disabled

Boolean Attributes

checked

HTML5 Types

<input type="search">

<input type="email">

<input type="url">

<input type="tel">

<input type="number">

<input type="date">

<input type="time">

<input type="datetime">

<input type="range">

<input type="color">

HTML5 Attributes

<input type="text" required>
<input type="number" disabled>
<input type="checkbox" checked>

Make sure a field is filled out

Don't allow the user to change a field

Set to be checked by default

JS Validation

Bind an event handler to the form's submit action

Check the form values inside the handler

Insert error messages into the DOM if needed

DOM Value Access

Checking input elements

var nameField = $("#name");

if (nameField.val()) {
    //all good
}

DOM Value Access

Checking textarea elements

var essayField = $("#essay");

if (essayField.val()) {
    //all good
}

DOM Value Access

Checkboxes - checked or not?

var agreeToTerms = $("#terms")[0];

if (agreeToTerms.checked) {
    //all good
}
var value = $('input[name="myRadio"]:checked').val();

Radio Buttons - which one is checked?

When to check forms

$("#myForm").on("submit", function(){

    // Do validation here

});

When the user submits the form

$("#myInput").on("blur", function(){

    // Do validation here

});

When the user moves away from the input element

Event Defaults

$("#myForm").on("submit", function(){
    // do error checking here...    

    if (found_errors) {
        return false;
    }
})

Return false stops the form from submitting

Event Defaults

$("#myForm").on("submit", function(){
    e.preventDefault();
})

This stops the form from submitting also

Processing and Validating Forms

By LizTheDeveloper

Processing and Validating Forms

  • 1,334