Input Validation with JavaScript

In addition to native ColdFusion input validation using the VALIDATE attribute of the CFINPUT and CFTEXTINPUT tags, the following tags support the ONVALIDATE attribute , which allows you to specify a JavaScript function to handle your CFFORM input validation:

JavaScript objects passed to the validation routine

The following JavaScript objects are passed by ColdFusion to the JavaScript function you specify in the ONVALIDATE attribute:

Handling failed validation

The ONERROR attribute allows you to specify a JavaScript function you want to execute in the event of a failed validation. For example, if you specify a JavaScript function to handle input validation in the ONVALIDATE attribute you can also specify a JavaScript function in the ONERROR attribute to handle a failed validation, which returns a false value. ONERROR is available in the following CFFORM tags:

When you specify a JavaScript routine in the ONERROR attribute, ColdFusion passes the following JavaScript objects to the specified routine:

Note To use JavaScript to validate form data:
  1. Create a new file in Studio.
  2. Edit the page so that it appears as follows:
    <HTML>
    <HEAD>
        <TITLE>JavaScript Validation</TITLE>
    
    <SCRIPT>
    <!--
    
    function testbox(form) {
    Ctrl = form.inputbox1;
    if (Ctrl.value == "" || Ctrl.value.indexOf ('@', 0) == -1) {
    return (false);
    } else
    return (true);
    } 
    
    //-->
    </SCRIPT>
    
    </HEAD>
    
    <BODY>
    <H2>JavaScript validation test</H2>
    
    <P>Please enter your email address:</P>
    <CFFORM NAME="UpdateForm"
        ACTION="update.cfm" >
    
        <CFINPUT TYPE="text"
            NAME="inputbox1"
            REQUIRED="YES"
    ONVALIDATE="testbox"
        MESSAGE="Sorry, invalid entry."
        SIZE="10"
        MAXLENGTH="10">
    
    <INPUT TYPE="Submit" VALUE=" Update... ">
    </CFFORM>
    
    </BODY>
    </HTML>
    
  3. Save the page as validjs.cfm.
  4. View validjs.cfm in your browser.

    When you enter an invalid email address, an error appears. Even if you enter a valide email address, and Error 404 appears because you haven't created the action page update.cfm.

Code Review
Code Description
<SCRIPT>
<!--

function testbox(form) {
    Ctrl = form.inputbox1;
    if (Ctrl.value == "" || Ctrl.value.indexOf 
('@', 0) == -1) {
    return (false);
    } else
        return (true);
} 

//-->
</SCRIPT>
JavaScript code to test for valid entry in text box.
ONVALIDATE="testbox"
Text box control parameter that calls the JavaScript test.

See the following Web site for information on JavaScript validation scripts: