JS form validation example

A quick JS example to get someome started using JavaScript form validation.

by mich

HTML

<form id="myform" action="someformontheinternet" method="post">
    <fieldset>
        <div>
            <label>First name</label>
            <input type="text" name="firstname" />
        </div>
        <div>
            <label>Last name</label>
            <input type="text" name="lastname" />
        </div>        
        <div>
            <label>Email</label>
            <input type="text" name="email" />
        </div>
        
        <div>
            <input type="submit" value="Sign up!" />
        </div>
    </fieldset>
</form>

CSS

body { padding: 5px; }
label {
    display:block;
    font-weight: bold;
}
input[type="text"] { border: solid 1px #777; padding: 3px;}
div { padding: 5px 0; border-bottom: solid 1px #EEE; }

JavaScript

(function() {
    
    var theForm = document.getElementById('myform');
    theForm.onsubmit = function(event) {
        event.preventDefault();
        //from here on the variable 'this' refers to the form, so you can access its elements by this.elemname.
        //example: 
        alert('First name:' + this.firstname.value);
        
        //if you've validated the form and wish to submit, just do this.submit();
    }
        
})();
//The wrapper around the code makes sure we're not polluting the global namespace (not creating global variables),
//which is good practice.