jQuery Validate

72721 단어 jQuery Validate
http://www.cnblogs.com/hejunrex/category/226234.html
 
    :http://bassistance.de/jquery-plugins/jquery-plugin-validation



jQuery plugin: Validation       



   :http://blog.sina.com.cn/s/blog_608475eb0100h3h1.html



 



   js 

<script src="../js/jquery.js" type="text/javascript"></script>

<script src="../js/jquery.validate.js" type="text/javascript"></script>



 



 、      

(1)required:true                    

(2)remote:"check.php"        ajax    check.php     

(3)email:true                                 

(4)url:true                                   

(5)date:true                                      ie6  ,  

(6)dateISO:true                           (ISO),  :2009-06-231998/01/22      ,      

(7)number:true                          (  ,  )

(8)digits:true                          

(9)creditcard:                              

(10)equalTo:"#field"                #field  

(11)accept:                                    (       )

(12)maxlength:5                      5    (       )

(13)minlength:10                     10    (       )

(14)rangelength:[5,10]               5   10       ")(       )

(15)range:[5,10]                       5   10   

(16)max:5                               5

(17)min:10                              10



 



 、     

messages: {

    required: "This field is required.",

    remote: "Please fix this field.",

    email: "Please enter a valid email address.",

    url: "Please enter a valid URL.",

    date: "Please enter a valid date.",

    dateISO: "Please enter a valid date (ISO).",

    dateDE: "Bitte geben Sie ein g ltiges Datum ein.",

    number: "Please enter a valid number.",

    numberDE: "Bitte geben Sie eine Nummer ein.",

    digits: "Please enter only digits",

    creditcard: "Please enter a valid credit card number.",

    equalTo: "Please enter the same value again.",

    accept: "Please enter a value with a valid extension.",

    maxlength: $.validator.format("Please enter no more than {0} characters."),

    minlength: $.validator.format("Please enter at least {0} characters."),

    rangelength: $.validator.format("Please enter a value between {0} and {1} characters long."),

    range: $.validator.format("Please enter a value between {0} and {1}."),

    max: $.validator.format("Please enter a value less than or equal to {0}."),

    min: $.validator.format("Please enter a value greater than or equal to {0}.")

},



     ,  js     :



jQuery.extend(jQuery.validator.messages, {

  required: "    ",

  remote: "      ",

  email: "            ",

  url: "        ",

  date: "        ",

  dateISO: "         (ISO).",

  number: "        ",

  digits: "      ",

  creditcard: "          ",

  equalTo: "         ",

  accept: "              ",

  maxlength: jQuery.validator.format("            {0}     "),

  minlength: jQuery.validator.format("            {0}     "),

  rangelength: jQuery.validator.format("           {0}   {1}       "),

  range: jQuery.validator.format("        {0}   {1}     "),

  max: jQuery.validator.format("        {0}   "),

  min: jQuery.validator.format("        {0}   ")

});



    ,      messages_cn.js ,      

<script src="../js/messages_cn.js" type="text/javascript"></script>1.          





<script src="../js/jquery.js" type="text/javascript"></script>

<script src="../js/jquery.validate.js" type="text/javascript"></script>

<script src="./js/jquery.metadata.js" type="text/javascript"></script>



$().ready(function() {

 $("#signupForm").validate();

});





<form id="signupForm" method="get" action="">

    <p>

        <label for="firstname">Firstname</label>

        <input id="firstname" name="firstname" class="required" />

    </p>

 <p>

  <label for="email">E-Mail</label>

  <input id="email" name="email" class="required email" />

 </p>

 <p>

  <label for="password">Password</label>

  <input id="password" name="password" type="password" class="{required:true,minlength:5}" />

 </p>

 <p>

  <label for="confirm_password">    </label>

  <input id="confirm_password" name="confirm_password" type="password" class="{required:true,minlength:5,equalTo:'#password'}" />

 </p>

    <p>

        <input class="submit" type="submit" value="Submit"/>

    </p>

</form>



  class="{}"   ,     :jquery.metadata.js



         ,      :

class="{required:true,minlength:5,messages:{required:'     '}}"



   equalTo    ,           ,    :

class="{required:true,minlength:5,equalTo:'#password'}"



 



2.       js   





$().ready(function() {

 $("#signupForm").validate({

        rules: {

   firstname: "required",

   email: {

    required: true,

    email: true

   },

   password: {

    required: true,

    minlength: 5

   },

   confirm_password: {

    required: true,

    minlength: 5,

    equalTo: "#password"

   }

  },

        messages: {

   firstname: "     ",

   email: {

    required: "   Email  ",

    email: "      email  "

   },

   password: {

    required: "     ",

    minlength: jQuery.format("      {0}    ")

   },

   confirm_password: {

    required: "       ",

    minlength: "        5   ",

    equalTo: "            "

   }

  }

    });

});



//messages ,        message,        





<form id="signupForm" method="get" action="">

    <p>

        <label for="firstname">Firstname</label>

        <input id="firstname" name="firstname" />

    </p>

 <p>

  <label for="email">E-Mail</label>

  <input id="email" name="email" />

 </p>

 <p>

  <label for="password">Password</label>

  <input id="password" name="password" type="password" />

 </p>

 <p>

  <label for="confirm_password">    </label>

  <input id="confirm_password" name="confirm_password" type="password" />

 </p>

    <p>

        <input class="submit" type="submit" value="Submit"/>

    </p>

</form>



 



required:true     

required:"#aa:checked"       ,     

required:function(){}    ,      

       ,              



 



 、         

1.          SUBMIT

$().ready(function() {

 $("#signupForm").validate({

        submitHandler:function(form){

            alert("submitted");   

            form.submit();

        }    

    });

});



  ajax  



 $(".selector").validate({     

 submitHandler: function(form) 

   {      

      $(form).ajaxSubmit();     

   }  

 }) 



    validate    ,    :

$.validator.setDefaults({

 submitHandler: function(form) { alert("submitted!");form.submit(); }

});



       ,     form.submit()     $(form).submit()



2.debug,        

       true,        ,     ,       



$().ready(function() {

 $("#signupForm").validate({

        debug:true

    });

});

                  debug, 

$.validator.setDefaults({

   debug: true

})



3.ignore:         

ignore: ".ignore"

4.           

errorPlacement:Callback



 Default:                

         ,     :error.appendTo(element.parent());                

errorPlacement: function(error, element) {  

    error.appendTo(element.parent());  

}



//





<tr>

    <td class="label"><label id="lfirstname" for="firstname">First Name</label></td>

    <td class="field"><input id="firstname" name="firstname" type="text" value="" maxlength="100" /></td>

    <td class="status"></td>

</tr>

<tr>

    <td style="padding-right: 5px;">

        <input id="dateformat_eu" name="dateformat" type="radio" value="0" />

        <label id="ldateformat_eu" for="dateformat_eu">14/02/07</label>

    </td>

    <td style="padding-left: 5px;">

        <input id="dateformat_am" name="dateformat" type="radio" value="1"  />

        <label id="ldateformat_am" for="dateformat_am">02/14/07</label>

    </td>

    <td></td>

</tr>

<tr>

    <td class="label">&nbsp;</td>

    <td class="field" colspan="2">

        <div id="termswrap">

            <input id="terms" type="checkbox" name="terms" />

            <label id="lterms" for="terms">I have read and accept the Terms of Use.</label>

        </div>

    </td>

</tr>



errorPlacement: function(error, element) {

    if ( element.is(":radio") )

        error.appendTo( element.parent().next().next() );

    else if ( element.is(":checkbox") )

        error.appendTo ( element.next() );

    else

        error.appendTo( element.parent().next() );

}



      :             <td class="status"></td> ,   radio   <td></td> ,    checkbox        



errorClass:String  Default: "error" 

       css  ,            



errorElement:String  Default: "label" 

         ,    label     em



errorContainer:Selector 

          ,                       ,      ,    

errorContainer: "#messageBox1, #messageBox2"



errorLabelContainer:Selector

               。



wrapper:String

          errorELement   



           ,                   ,           



errorContainer: "div.error",

errorLabelContainer: $("#signupForm div.error"),

wrapper: "li"



5           

         ,        ,            validation.css             



 



input.error { border: 1px solid red; }

label.error {

  background:url("./demo/images/unchecked.gif") no-repeat 0px 0px;



  padding-left: 16px;



  padding-bottom: 2px;



  font-weight: bold;



  color: #EA5200;

}

label.checked {

  background:url("./demo/images/checked.gif") no-repeat 0px 0px;

}



6            

success:String,Callback

              ,        ,     css ,       

success: function(label) {

    // set &nbsp; as text for IE

    label.html("&nbsp;").addClass("checked");

    //label.addClass("valid").text("Ok!")

}

  "valid"      ,  CSS      <style>label.valid {}</style>

success: "valid"



 



7         

      boolean  ,        false,      。



onsubmit:Boolean  Default: true 

     .    false         

onfocusout:Boolean  Default: true 

       (   checkboxes/radio buttons)

onkeyup:Boolean  Default: true 

 keyup   .

onclick:Boolean  Default: true 

 checkboxes   radio      

focusInvalid:Boolean  Default: true 

     ,        (                     )     

focusCleanup:Boolean  Default: false 

   true                ,      。    focusInvalid    



 



//     

$().ready(function() {

 var validator = $("#signupForm").validate({

        submitHandler:function(form){

            alert("submitted");   

            form.submit();

        }    

    });

    $("#reset").click(function() {

        validator.resetForm();

    });



});



8    

remote:URL

  ajax      ,                ,          ,    data  



remote: "check-email.php"



remote: {

    url: "check-email.php",     //      

    type: "post",               //      

    dataType: "json",           //         

    data: {                     //      

        username: function() {

            return $("#username").val();

        }

    }

}





         "true"   "false",       



 



9       

addMethod:name, method, message

       





//        

jQuery.validator.addMethod("byteRangeLength", function(value, element, param) {

    var length = value.length;

    for(var i = 0; i < value.length; i++){

        if(value.charCodeAt(i) > 127){

            length++;

        }

    }

  return this.optional(element) || ( length >= param[0] && length <= param[1] );   

}, $.validator.format("        {0}-{1}     (      2   )"));





//          

jQuery.validator.addMethod("isZipCode", function(value, element) {   

    var tel = /^[0-9]{6}$/;

    return this.optional(element) || (tel.test(value));

}, "           ");



 



1.  additional-methods.js        jquery.validate.js  

      additional-methods.js   



2. messages_cn.js    :isZipCode: "       、    、      ",



       additional-methods.js     。



 



 



10radio checkbox、select   

 



1.radio required        

<input  type="radio" id="gender_male" value="m" name="gender" class="{required:true}" />

<input  type="radio" id="gender_female" value="f" name="gender"/>



 



2.checkbox required      

<input type="checkbox" class="checkbox" id="agree" name="agree" class="{required:true}" />



checkbox minlength           ,maxlength         ,rangelength:[2,3]         





<input type="checkbox" class="checkbox" id="spam_email" value="email" name="spam[]" class="{required:true, minlength:2}" />

<input type="checkbox" class="checkbox" id="spam_phone" value="phone" name="spam[]" />

<input type="checkbox" class="checkbox" id="spam_mail" value="mail" name="spam[]" />



 



    3.select required     value    

<select id="jungle" name="jungle" title="Please select something!" class="{required:true}">

    <option value=""></option>

    <option value="1">Buga</option>

    <option value="2">Baga</option>

    <option value="3">Oi</option>

</select>



 



select minlength         (    select),maxlength          ,rangelength:[2,3]        

<select id="fruit" name="fruit" title="Please select at least two fruits" class="{required:true, minlength:2}" multiple="multiple">

    <option value="b">Banana</option>

    <option value="a">Apple</option>

    <option value="p">Peach</option>

    <option value="t">Turtle</option>

</select>



 



 



jQuery.validate   API   





  



    



  



validate(options)



  :Validator



     FORM



valid()



  :Boolean



        



rules()



  :Options



         



rules("add",rules)



  :Options



      



rules("remove",rules)



  :Options



      



removeAttrs(attributes)



  :Options



            



Custom selectors



:blank



  :Validator



       



:filled



  :Array <Element 

>



      



:unchecked



  :Array <Element 

>



          



Utilities



jQuery.format



(template,argument 

,argumentN...)



  :String



          

{n}





Validator:



validate      Validator  ,      ,                form   . validator       ,          



form()



  :Boolean



  form        



element(element)



  :Boolean



             



resetForm()



  :undefined



      FORM           



showErrors(errors)



  :undefined



         



Validator functions:



setDefaults(defaults)



  :undefined



       



addMethod(name,method,message)



  :undefined



          .              ,  JAVASCRIPT           



addClassRules(name,rules)



  :undefined



                           



addClassRules(rules)



  :undefined



                           ,         





      :



required()



  :Boolean



      



required(dependency-expression)



  :Boolean



             



required(dependency-callback)



  :Boolean



              



remote(url)



  :Boolean



      。url           



minlength(length)



  :Boolean



      



maxlength(length)



  :Boolean



      



rangelength(range)



  :Boolean



        [min,max]



min(value)



  :Boolean



     



max(value)



  :Boolean



     



email()



  :Boolean



        



range(range)



  :Boolean



      



url()



  :Boolean



  URL  



date()



  :Boolean



      (  30/30/2008   ,             )



dateISO()



  :Boolean



  ISO       



dateDE()



  :Boolean



         (29.04.1994 or 

1.1.2006)



number()



  :Boolean



       (     )



digits()



  :Boolean



    



creditcard()



  :Boolean



      



accept(extension)



  :Boolean



           



equalTo(other)



  :Boolean



              



phoneUS()



  :Boolean



         





validate ()    :



debug:      (     ):



$(".selector").validate



({



   debug:true



})



        :



$.validator.setDefaults({



   debug:true



})



submitHandler:



          ,            ,        



$(".selector").validate({



   submitHandler:function(form) 

{



$(form).ajaxSubmit();



   }



})



ignore:



          



$("#myform").validate({



   ignore:".ignore"



})



rules:



     ,key:value   ,key       ,value         



$(".selector").validate({



   rules:{



     name:"required",



     email:{



       required:true,



       email:true



     }



   }



})



messages:



        key:value   key       ,        



$(".selector").validate({



   rules:{



     name:"required",



     email:{



       required:true,



       email:true



     }



   },



   messages:{



     name:"Name    ",



     email:{



       

required:"E-mail    ",



       email:"E-mail     "



     }



   }



})



groups:



        ,       , error Placement           



$("#myform").validate({



  groups:{



    username:"fname 

lname"



  },



  

errorPlacement:function(error,element) {



     if (element.attr("name") == 

"fname" || element.attr("name") == "lname")



       

error.insertAfter("#lastname");



     else



       

error.insertAfter(element);



   },



   debug:true



})



Onubmit Boolean   :true



       



$(".selector").validate({



   

onsubmit:false



})



onfocusout Boolean   :true  



          



$(".selector").validate({



   

onfocusout:false



})



onkeyup Boolean   :true  



          



$(".selector").validate({



   onkeyup:false



})



onclick Boolean   :true



          (    checkbox,radiobox)



$(".selector").validate({



   onclick:false



})



focusInvalid Boolean   :true



     ,        (                     )     



$(".selector").validate({



   focusInvalid:false



})



focusCleanup Boolean   :false



              ,       (    focusInvalid.    )



$(".selector").validate({



   focusCleanup:true



})



errorClass String   :"error"



       css  ,            



$(".selector").validate({



   

errorClass:"invalid"



})



errorElement String   :"label"



          



$(".selector").validate



   errorElement:"em"



})



wrapper String



           errorELement   



$(".selector").validate({



   wrapper:"li"



})



errorLabelContainer Selector



               



$("#myform").validate({



   

errorLabelContainer:"#messageBox",



   wrapper:"li",



   submitHandler:function() { 

alert("Submitted!") }



})





showErrors:



     ,                  



$(".selector").validate({



   

showErrors:function(errorMap,errorList) {



        $("#summary").html("Your 

form contains " + this.numberOfInvalids() + " errors,see details 

below.");



        

this.defaultShowErrors();



   }



})



errorPlacement:



     ,           



$("#myform").validate({



  

rrorPlacement:function(error,element) {  

error.appendTo(element.parent("td").next("td"));



   },



   debug:true





})



success:



              ,        ,     css ,       



$("#myform").validate({



        

success:"valid",



        submitHandler:function() 

{ alert("Submitted!") }



})



highlight:



              ,   







addMethod(name,method,message)  :



  name         



  method     ,      (value,element,param) 

value     ,element      

param   ,     addMethod    built-in Validation 

methods               ,       ,   a-f,    :





$.validator.addMethod("af",function(value,element,params){



   

if(value.length>1){



    return false;



   }



   if(value>=params[0] 

&& value<=params[1]){



    return true;



   }else{



    return false;



   }



},"       , a-f");



    ,         id="username",  rules  



username:{



   af:["a","f"]



}





addMethod      ,            ,   af



addMethod      ,          ,      :"       , a-f"



addMethod      ,     ,      ,              



        ,   ,  af:"a",  a         ,      ,  [] ,     





meta String  :



$("#myform").validate({



   meta:"validate",



   submitHandler:function() { 

alert("Submitted!") }



})



<script type="text/javascript" 

src="js/jquery.metadata.js"></script>



<script type="text/javascript" 

src="js/jquery.validate.js"></script>



<form id="myform">



  <input type="text" 

name="email" class="{validate:{ required:true,email:true }}" />



  <input type="submit" 

value="Submit" />



</form>

좋은 웹페이지 즐겨찾기