Using jQuery validator's valid() or element() method with remote methods

前端 未结 1 1006
無奈伤痛
無奈伤痛 2021-01-23 14:52

jQuery validator valid() method ( http://jqueryvalidation.org/valid) checks whether the selected form is valid or whether all selected elements are valid.

j

相关标签:
1条回答
  • 2021-01-23 15:37

    Kind of a hack, but it seems to work. I don't like how it initiates two ajax requests. I suppose I could dynamically change the rules to remove the remote method from validator's rules, however, then I would need to manually add the message. Technically for my application, I don't need the message displayed, but am using return input.next().html(); to get the message as shown in https://jsfiddle.net/vctt9utd/.

    http://jsfiddle.net/msprwad5/

    <form id="myForm" method="post">
        <input name="myelement" id="myelement" value="">
    </form>
    <button id="testit">testit</button>
    
     var validator = $("#myForm").validate({
         rules: {
             myelement: {
                 minlength: 2,
                 maxlength: 4,
                 required: true,
                 remote: {
                     url: "/echo/html/",
                     type: "POST",
                     data: {
                         html: 0,
                         delay: .5
                     }
                 }
             }
         },
         messages: {
             myelement: {
                 remote: "error message"
             }
         }
     });
    
     $('#testit').click(function () {
         if ($('#myelement').valid()) {
             $.post("/echo/html/", {
                 html: 0,
                 delay: .5
             }, function (status) {
                 if(!+status){alert('failed remote validation');}
             });
         }
         else {alert('failed normal validation if first attempt, otherwise could be either.');}
     })
    
    0 讨论(0)
提交回复
热议问题