Appendix JS_F_A1-A3-A4

Summary

Requirement: If an input error is detected, the field should be identified and the error described in text.

Details:

  • JS_F_A1: Form validation should be triggered by submission, rather than individual field events.
  • JS_F_A3: Form validation should trigger an alert then set focus on the first invalid field.
  • JS_F_A4: Validation error messages should be programmatically inserted directly after the field they relate to, using functions of the DOM.

Examples

Correct code

Refer to the JS_F_A1-A3-A4 live demo for working examples.

<form id="demo" action="..." method="get">
    <fieldset>
        <p>
            <label for="username">Username:</label>
            <input id="username" name="username" type="text" />
        </p>
        <p>
            <label for="email">Email:</label>
            <input id="email" name="email" type="text" />
        </p>
    </fieldset>
    <fieldset>
        <button type="submit">Submit</button>
    </fieldset>
</form>
var form = document.getElementById('demo');
 
form.addEventListener('submit', function(e)
{
    var labels = form.getElementsByTagName('label');
    for(var i = 0; i < labels.length; i ++)
    {
        if(labels[i].className == 'error')
        {
            labels[i].parentNode.removeChild(labels[i]);
            i --;
        }
    }
 
    var messages = [];
    if(form.username.value === '')
    {
        messages.push([
            'username', 
            'Please enter a username']);
    }
    else if(!/^[- \w]+$/i.test(form.username.value))
    {
        messages.push([
            'username', 
            'Your username cannot contain '
                + 'any special characters']);
    }
    if(form.email.value === '')
    {
        messages.push([
            'email', 
            'Please enter an email address']);
    }
    else if(!/^[-\w]+(\.[-\w]+)*[@][-\w]+(\.[-\w]+)+$/i
        .test(form.email.value))
    {
        messages.push([
            'email', 
            'The email address you gave is not valid']);
    }
 
    if(messages.length > 0)
    {
        alert('Your form had errors in it. '
            + 'Please correct the indicated problems '
            + 'and then submit again.');
 
        for(var i = 0; i < messages.length; i ++)
        {
            var field = form[messages[i][0]];
 
            var label = document.createElement('label');
            label.htmlFor = field.id;
            label.className = 'error';
            var message = label.appendChild(
                document.createElement('strong'));
            message.appendChild(
                document.createTextNode(
                    messages[i][1]));
 
            field.parentNode.appendChild(label);
 
            if(i == 0)
            {
                field.focus();
            }
        }
 
        e.preventDefault();
    }
}, false);