开发者

Is it possible to know with jQuery-validate when a single field validation has failed

I have a form where I need to do additional processing when a single field validation has failed (when the user tabs out of the filed for instance, but th开发者_如何学编程e form has not been submitted) how can I hook up to this event with jquery-validate?


To know if there has been an error in the form, use:

if(!$("#form0").valid()){
  //There was one or more errors in the form
}

To know if a specific element has an error, use:

if(!$("#form0").validate().element($("#text1"))){
  //There where some error in #text1
}

(Note that this two methods will also trigger validations)

Hope this helps. Cheers


I'm using a combination of overriding the highlight/unhighlight myself.

//Update the validator's highlight/unhighlight
$.validator.setDefaults({
  ignoreTitle:true
  ,highlight: function (element) {
    var el = $(element);
    //TODO: Handle UI changes, add/remove classes
    el.trigger("validate.fail");
  }
  ,unhighlight: function (element) {
    var el = $(element)
    //TODO: Handle UI changes, add/remove classes
    el.trigger("validate.success")
  }
});

Now, I can simply bind to the validate.fail method...

$("#myInputElement").bind("validate.fail",function(){
  //TODO: Do something with this knowledge.
});

NOTE: I have done this in the past to integrate jQuery with bootstrap's UI conventions... it's worked pretty well.


When you set up your validation, you should be saving the validator object. you can use this to validate individual fields.

<script type="text/javascript">
var _validator;
$(function () {
    _validator = $("#form").validate();   
});
function doSomething() {
    _validator.element($('#someElement'));
}
</script>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜