使用jQuery验证字段组

时间:2021-12-23 02:58:36

Let's say I have a form with email and phone fields and I want to check if at least one them is correct. I mean, I'm ok with user entering valid phone and invalid email. Is there a way to do this using jQuery validation plug-in? (I wasn't able to find a set of options to cover all the cases and ended up coding it by hand)

假设我有一个包含电子邮件和电话字段的表单,我想检查它们中是否至少有一个是正确的。我的意思是,我很高兴用户输入有效的电话和无效的电子邮件。有没有办法使用jQuery验证插件? (我无法找到一套涵盖所有案例的选项,最后手工编写)

1 个解决方案

#1


2  

There's a plugin I wrote for validating fields in jQuery which will do what you want rather well.

我为jQuery中的字段验证了一个插件,它可以很好地完成您想要的操作。

Warning: I genuinely think this is the best solution for your problem, but don't just take my word for it because I can't be objective.

警告:我真的认为这是解决问题的最佳方法,但不要只听我的话,因为我不能客观。

You can get the plugin here: http://plugins.jquery.com/project/validate-field

你可以在这里获得插件:http://plugins.jquery.com/project/validate-field

To do what you require:

做你需要的:

$('#email,#phone').validateField({
    notEmpty: function (val) { // if this function returns true, the field must not be empty
        return ($('#email:blank,#phone:blank').size() > 1);
    },
    message: 'Please fill in either the Email or Phone field',
    validateOn: '#email,#phone',
    validateEvent: 'change'
});

Edit: added validateOn and validateEvent to make sure the errors on both objects are cleared when one is filled in.

编辑:添加了validateOn和validateEvent以确保在填写一个对象时清除两个对象上的错误。

#1


2  

There's a plugin I wrote for validating fields in jQuery which will do what you want rather well.

我为jQuery中的字段验证了一个插件,它可以很好地完成您想要的操作。

Warning: I genuinely think this is the best solution for your problem, but don't just take my word for it because I can't be objective.

警告:我真的认为这是解决问题的最佳方法,但不要只听我的话,因为我不能客观。

You can get the plugin here: http://plugins.jquery.com/project/validate-field

你可以在这里获得插件:http://plugins.jquery.com/project/validate-field

To do what you require:

做你需要的:

$('#email,#phone').validateField({
    notEmpty: function (val) { // if this function returns true, the field must not be empty
        return ($('#email:blank,#phone:blank').size() > 1);
    },
    message: 'Please fill in either the Email or Phone field',
    validateOn: '#email,#phone',
    validateEvent: 'change'
});

Edit: added validateOn and validateEvent to make sure the errors on both objects are cleared when one is filled in.

编辑:添加了validateOn和validateEvent以确保在填写一个对象时清除两个对象上的错误。