views:

640

answers:

3

How can I do form validation with jQuery to allow a green check mark if a field passes a regex and a red x if it fails?

Can anyone point me to an example of some jQuery that shows one icon immediately if a field validates and a different one if it fails?

+1  A: 

There are a variety of ways to implement this. Here is one.

The relevant HTML would look like this:

<div><input type="text" id="myInput" /></div>

The jQuery would be something like this:

// probably within your jQuery(document).ready(...) function:
// bind a change event handler to your input
jQuery("#myInput").bind("change", function(e) {

    var $this = jQuery(this);
    var re = /[a-z]/; // here's your regex
    var imgSrc = "blank.gif";

    if (re.test(jQuery(this).val())){
        // this is a successful match - green
        imgSrc = "green.gif";         
    } else {
       // this is not a match - red
       imgSrc = "red.gif";
    }

    // make sure we have an image before our input:
    if(!$this.prev().is("img")) { $this.before("img"); }

    // set the image to green
    $this.prev().attr("src", imgSrc);
});

Edit: bug fix + comments

Jeff Meatball Yang
@Jeff Yang, This is good. Can you think of a way we make extract out most of this into a method so there wont be so much repeated code for each field?
+2  A: 

There's the jQuery Validation plugin which supports that sort of thing. Take a look at the "Remember the Milk" demo form; it has immediate feedback. You'd set up the "success" option in the validate() method to do more than just provide negative feedback.

Vitorio
A: 
$(document).ready(AddValidation);

function AddValidation()
{
    $("#frmadminlogin").validate({
        'rules':{
            'txtadminemail':{'required':true, 'email':true},
            'txtadminpass':{'required':true}
        },
        'messages': {
            'txtadminemail':{'required':'<img title="Please enter login email." src="../images/error.gif" />', 'email':'<img title="Please enter valid email." src="../images/error.gif" />'},
            'txtadminpass':{'required':'<img title="Please enter login password." src="../images/error.gif" />'}
        }
    });
}
zawmn83