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

半腔热情 提交于 2019-12-23 19:00:48

问题


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 the form has not been submitted) how can I hook up to this event with jquery-validate?


回答1:


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




回答2:


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.




回答3:


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>


来源:https://stackoverflow.com/questions/5898673/is-it-possible-to-know-with-jquery-validate-when-a-single-field-validation-has-f

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!