简体   繁体   English

jQuery Validate Plugin - 触发单个字段的验证

[英]jQuery Validate Plugin - Trigger validation of single field

I've got a form that can optionally be pre-populated via facebook connect.我有一个可以选择通过 facebook connect 预先填充的表单。 Once a user connects, their name and email are automatically filled in. The problem is that this doesn't trigger the remote validation to check if the email already exists.一旦用户连接,他们的姓名和电子邮件将自动填写。问题是这不会触发远程验证以检查电子邮件是否已存在。

Is there a way I could call the validation on that field alone?有没有办法可以单独调用该字段的验证? Something like:就像是:

$('#email-field-only').validate()

would be idea.将是想法。 Searched through the docs with no luck.在没有运气的情况下搜索了文档。

这种方法似乎可以满足您的需求:

$('#email-field-only').valid();

Use Validator.element() :使用Validator.element()

Validates a single element, returns true if it is valid, false otherwise.验证单个元素,如果有效则返回真,否则返回假。

Here is the example shown in the API:以下是 API 中显示的示例:

var validator = $( "#myform" ).validate();
validator.element( "#myselect" );

.valid() validates the entire form, as others have pointed out. .valid()验证整个表单,正如其他人指出的那样。 The API says: API 说:

Checks whether the selected form is valid or whether all selected elements are valid.检查选定的表单是否有效或是否所有选定的元素都有效。

For some reason, some of the other methods don't work until the field has been focused/blured/changed, or a submit has been attempted... this works for me.出于某种原因,在该字段被聚焦/模糊/更改或尝试提交之前,其他一些方法不起作用......这对我有用。

$("#formid").data('validator').element('#element').valid();

Had to dig through the jquery.validate script to find it...不得不挖掘 jquery.validate 脚本才能找到它......

$("#FormId").validate().element('#FieldId');

If you want to validate individual form field, but don't want for UI to be triggered and display any validation errors, you may consider to use Validator.check() method which returns if given field passes validation or not.如果您想验证单个表单字段,但不想触发 UI 并显示任何验证错误,您可以考虑使用 Validator.check() 方法,该方法返回给定字段是否通过验证。

Here is example这是例子

var validator = $("#form").data('validator');
if(validator.check('#element')){
    /*field is valid*/
}else{
    /*field is not valid (but no errors will be displayed)*/
}

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> 

-- cross posted with this similar question - 交叉发布了这个类似的问题

in case u wanna do the validation for "some elements" (not all element) on your form.You can use this method:如果您想对表单上的“某些元素”(不是所有元素)进行验证。您可以使用此方法:

$('input[name="element-one"], input[name="element-two"], input[name="element-three"]').valid();

Hope it help everybody :)希望对大家有帮助:)

EDITED已编辑

$("#element").validate().valid()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM