jQuery dynamic validation

前端 未结 4 448
野的像风
野的像风 2021-01-22 09:10

Hi there Im trying to do a few things with jQuery validation plugin and seems stuck on one place.

Here is some code:



        
4条回答
  •  终归单人心
    2021-01-22 09:57

    You might consider something like the below. It's a bit clearer to read and debug. Since you are using standard rules like "required", you don't have to specify a message unless you want something different. The rules and messages are identified by the name of the input field (e.g. email).

    The errorPlacement option is where you specify the location of the messages. You don't have to include this option; the default is to append the message to the input field. But if you have layout divs or need special position for message on radio boxes, or what have you, this is the place to do it.

    $(document).ready(function(){ 
        $('#myform').validate({ 
          rules:{
            email: "required", 
            phone: {required:true, minlength:7}
          },
          messages:{ //not required as default message for "required" rule makes same text
            email: "email is required", 
            phone: "phone is required",
          },
          errorPlacement: function(error, element) { //this is where to put positioning rules
            error.appendTo(element.parent()); //just an example
          }
       });
    });
    

提交回复
热议问题