Your Ad Here
DOM

Bookmark and Share
DOM with JavaScript validation

Another very popular use of JavaScript is form validation - verifying the data entered into an online form. In the next example, I'll be using the DOM and some simple JavaScript to ensure that the checkbox is ticked and the email address entered into the text field is in the correct format. Here's the form:

<html>
<head>
</head>
<body>
    <form action="somescript.cgi"
    method="post"
    onSubmit="return check();">
    Email address:
    <br>
    <input id="email"
        type="text"
        name="email"
        size="30">
    <br>
    <input id="spam_me" type="Checkbox" name="spam_me">Yes, I  
    want you to send me megabytes of useless advertisements via  
    email. I love buying crummy products from people who  
    probably flunked kindergarten.
    <br>
    <input type="submit">
    </form>
</body>

</html>

And here's the validation script:

<script language="JavaScript">
function checkEmail(){
    // get to the field
    var obj = document.getElementById("email");

    // value of field
    var str = obj.value;

    // define pattern to match email address
    var pattern =
    /^([a-zA-Z0-9])+([\.a-zA-Z0-9_-])*@([a-zA-Z0-9_-])+
    (\.[a-zA-Z0-9_-]+)+/;

    // match the string to the pattern
    var flag = pattern.test(str);

    if(!flag){
        alert ("Please enter a valid email address");
        return false;
    } else {
        return true;
    }
}
function checkSpam(){
    // get to the field
    var obj = document.getElementById("spam_me");

    // checkbox ticked?
    if (obj.checked){
        return true;
    } else {
        alert ("Please check the box");
        return false;
    }
}
function check(){
    // perform validation and submit form if all is well
    if(checkEmail() && checkSpam()){
        return true;
    }else {
        return false;
    }
}
</script>

As you can see, the form is submitted only after receiving a positive (true) result from the JavaScript function check(). This function, in turn, calls the functions checkEmail() and checkSpam(),which first obtain references to their respective form elements and then check their values for validity.

Today's Deal