Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery validate success indicator

Ok, I think I have this wrong...but I cant seem to get the answer. Im just trying to create a success checkmark or indicator that what the user has entered into the input form is valid. The commented out portion of the script is the idea of what Im trying to achieve. Here is the script:

$('document').ready(function(){
    $('form').validate({
        rules: {
           a: {required:true, minlength:2},
           b: {required:true}
        },      
        messages: {
           a: {required: "enter your name!"},
           b: {required: "enter the date!"}                        
        },
        errorPlacement: function(error, element) {
        if(element.attr('name') == 'a'){
             $('#name').html(error);                
         }
         if(element.attr('name') == 'b'){
             $('#date').html(error);                
         }
        },
        success: function(error){
            //a: {$('#name').html('nice name!');},
            //b: {$('#date').html('nice date!');}                           
        },
        debug:true
    });
    $('#a').blur(function(){
        $("form").validate().element("#a");
    });
});

And here is the html:

<form action="#" id='commentForm'>
    <input type="text" name="a" id="a">
    <input type="text" name="b" id="b">
    <button type="submit">Validate!</button>
<div id="date" style="border:1px solid blue;"></div>
<div id="name" style="border:1px solid red;"></div>
</form>

Last, but not least, here is the jsfiddle:

http://jsfiddle.net/mmw562/wQxQ8/8/

Many thanks in advance for your help!

like image 540
user791187 Avatar asked Nov 24 '12 19:11

user791187


1 Answers

The part inside success: would be a class name or a JavaScript callback function, which looks just like any other function. But instead, you wrote it like an array of plugin options. Also, since it's called "success", why would error be passed into it when there wouldn't be any? As per the documentation it should look something like this...

success: function(label){
    label.addClass("valid").text("Ok!");                        
},

http://docs.jquery.com/Plugins/Validation/validate#toptions

If specified, the error label is displayed to show a valid element. If a String is given, its added as a class to the label. If a Function is given, its called with the label (as a jQuery object) as its only argument. That can be used to add a text like "ok!".

Here is your jsFiddle slightly modified to show the basic concept. Perhaps you can use a checkmark as a background-image in the CSS of the .valid class.

http://jsfiddle.net/wQxQ8/12/

like image 174
Sparky Avatar answered Sep 17 '22 12:09

Sparky