Validating forms

We can use JavaScript to validate the content of a form before submitting it to a CGI web server.

For example:

Checking an email address

We can't check that an email address is genuine, but we can check that it appears to be genuine, by:

Email:

// JavaScript
function checkEmail(id)
{
    var email = document.getElementById(id).value;
    // alert(email);
    
    var atPos = email.indexOf("@");
    var dotPos = email.lastIndexOf(".");
    if((atPos < 1) ||              // It contains an @ and not as the first character
       (dotPos < atPos+2) ||       // Check there is a dot at least 2 chars after the @
       (dotPos > email.length-2))  // Check the dot isn't the last character
    {
        alert("EMail address is invalid");
        return false;
    }
    return true;
}

<!-- The HTML -->
<form type='get' action='#' onsubmit="return checkEmail('email')">
<p>Email: <input type='text' size='40' name='email' id='email' /></p>
<p><input type='submit' value='Submit' /></p>
</form>

[Download]

Checking a sequence is long enough

We simply extract the sequence remove white space and line breaks and see how many characters are left.

Sequence:

// JavaScript
function checkSequence(id, minLen)
{
    var sequence = document.getElementById(id).value;
    // alert(sequence);
    
    sequence = sequence.replace(/\s/g,"");
    // alert(sequence);

    if(sequence.length < minLen)
    {
        var msg = "Your sequence must contain at least " + minLen + " residues";
        alert(msg);
        return false;
    }
    return true;
}

<!-- The HTML -->
<form type='get' action='#' onsubmit="return checkSequence('seq', 20)">
<p>Sequence:<br />
<textarea cols='60' rows='5' name='seq' id='seq' /></textarea>
<p><input type='submit' value='Submit' /></p>
</form>

[Download]

Continue