HTML5 Form Validation

by TJ VanToll

HTML

<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1">
<form>
    <div>
        <label for="name">Name:</label>
        <input type="text" name="name" id="name" required="required" data-invalid-message="Name is required."/>
    </div>
    <div>
        <label for="email">Email:</label>
        <input type="email" name="email" id="email" required="required" data-invalid-message="You must provide a valid email address."/>
    </div>
    <div>
        <button>Submit</button>
    </div>
</form>

CSS

* { box-sizing: border-box; }
body {
    font-size: 1.2em;
}
body input, body button {
    font-size: 1.2em;
}

form > div {
    margin: 1em;
}
form button {
    width: 100%;
}
label { display: block; }
input {
    width: 100%;
    padding: 0.2em;
}
button {
    padding: 0.2em;
}
.invalid {
    background: red;
    color: white;
}
.error {
    color: red;
}

JavaScript

$( "input" ).on( "blur invalid", function() {
    var message = $( this ).attr( "data-invalid-message" );
    $( this )
        .removeClass( "invalid" )
        .next( ".error" ).remove();
    
    if ( !this.validity.valid ) {
        $( this )
            .addClass( "invalid" )
            .after( "<span class='error'>" + message + "</span>" );
    }
});

// Turn off the bubbles
$( "input" ).on( "invalid", false );

// Support: Safari, iOS Safari, default Android browser
$( "form" ).on( "submit", function( event ) {
    if ( !this.checkValidity() ) {
        event.preventDefault();
    }
});

document.querySelector( "form" ).addEventListener( "submit", function() {
    alert( "Successful submission" ); 
});