jQuery 验证优雅的条件逻辑

发布于 2024-11-29 17:03:12 字数 485 浏览 0 评论 0原文

我正在使用 jQuery 验证插件验证表单(需要使用该插件,因为我有其他功能需要该插件)。它具有以下字段:

phoneNumber 名字 姓氏 城市 zip

当以下语句之一为真时,该表单被视为有效:

  • phoneNumber 有效
  • firstName lastName city 都是有效的
  • firstName lastName zip 都是有效的

我知道如何要求每个字段并使用其他验证方法(我什至有自己的拉链),但我正在尝试找出一个优雅的实现我上面描述的逻辑的解决方案。自定义方法或验证组是处理此问题的最佳方法吗?

I am validating a form with the jQuery validation plugin (using the plugin is required, as I have other functionality that needs the plugin). It has the following fields:

phoneNumber
firstName
lastName
city
zip

The form is considered valid when one of the following statements is true:

  • phoneNumber is valid
  • firstName lastName city are all valid
  • firstName lastName zip are all valid

I know how to require each field and use the other validation methods (I even have my own for the zip), but I am trying to figure out an elegant solution to implement the logic I described above. Is a custom method or validation groups the best way to handle this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

野生奥特曼 2024-12-06 17:03:12

情人眼里出西施……

我建议制作一个自定义验证器来处理您所拥有的三种情况。

我花了一段时间来了解验证可以做什么...我想出了这个来验证我的表单。我使用了对 servlet 的异步调用来检查我的用户名...但是您可以在其中放入您想要的内容。

我发现另一篇关于堆栈溢出的文章更详细地说明了如何制作自定义验证器......
我特别喜欢这行 jQuery.validator.methods['date'].call(this,value,element) 因为您似乎可以在自定义代码中使用内置验证器。 jQuery 验证插件 - 如何创建简单的自定义规则?

这些是我在学习验证时使用的资源:
http://www.ferdychristant.com/blog//articles/DOMM-7LZJN7< /a> //详细介绍如何真正使用验证的文章。
http://www.ferdychristant.com/blog//pages/jQuery% 20验证%20代码
http://randomactsofcoding.blogspot.com/ 2008/10/starting-with-jquery-how-to-write.html
http://docs.jquery.com/Plugins/Validation/Methods/ required#dependency-expression

http://docs.jquery.com/Plugins/Validation ...您只需点击全部即可!

下面您还会看到可以将 javascript 直接放入规则部分。

$(document).ready(function() {

$("#EmailUserEditFormId").validate({

    debug: true, //this lets it hit firebug
    onkeyup:false, //keep the traffic down for my async call

    rules: {

        username: {
            required: (jQuery('input#username:disabled').length==1)?false:true, //example of JS in a rule
            usernameCheck: (jQuery('input#username:disabled').length==1)?false:true //example of a JS rule with a custom validator 
        }
    },

    messages: {
        username: {
            required: "Please enter a unique username.",
            usernameCheck: "Username is already in use. Choose another."
        }
    }

});

});

...这是我的简单自定义验证器。

jQuery.validator.addMethod('usernameCheck', function(username) {
var postURL = "CheckUsername";
$.ajax({
    cache: false,
    async: false,
    type: 'POST',
    data: 'username=' + username,
    datatype: 'xml',
    url: postURL,
    success: function(xml) {
        unique = (jQuery(xml).find('unique').text() == "true") ? true : false;
    }
});
return unique;

}, '');

Elegant is in the eye of the beholder...

I would recommend making a custom validator to handle the three cases that you have.

I spent a while to understand what Validate could do... I came up with this to validate my form. I used an async call to a servlet to do my username check... but you can put what ever you want in it.

I found another post on stack overflow that greater illustrates making custom validators...
I particularly like this line jQuery.validator.methods['date'].call(this,value,element) as it seems you can use the built in validators within your custom code. jQuery Validate Plugin - How to create a simple custom rule?

These are the resources I used in learning about validate:
http://www.ferdychristant.com/blog//articles/DOMM-7LZJN7 //article detailing how to really use validate.
http://www.ferdychristant.com/blog//pages/jQuery%20validation%20code
http://randomactsofcoding.blogspot.com/2008/10/starting-with-jquery-how-to-write.html
http://docs.jquery.com/Plugins/Validation/Methods/required#dependency-expression

There is also an amazing depth of information simply in http://docs.jquery.com/Plugins/Validation ...you just gotta click through it all!

below you will also see that you can put javascript right into the rules section.

$(document).ready(function() {

$("#EmailUserEditFormId").validate({

    debug: true, //this lets it hit firebug
    onkeyup:false, //keep the traffic down for my async call

    rules: {

        username: {
            required: (jQuery('input#username:disabled').length==1)?false:true, //example of JS in a rule
            usernameCheck: (jQuery('input#username:disabled').length==1)?false:true //example of a JS rule with a custom validator 
        }
    },

    messages: {
        username: {
            required: "Please enter a unique username.",
            usernameCheck: "Username is already in use. Choose another."
        }
    }

});

});

...and this was my simple custom validator.

jQuery.validator.addMethod('usernameCheck', function(username) {
var postURL = "CheckUsername";
$.ajax({
    cache: false,
    async: false,
    type: 'POST',
    data: 'username=' + username,
    datatype: 'xml',
    url: postURL,
    success: function(xml) {
        unique = (jQuery(xml).find('unique').text() == "true") ? true : false;
    }
});
return unique;

}, '');

感情洁癖 2024-12-06 17:03:12
phoneNumberValid, firstNameValid, lastNameValid, cityValid, zipValid;
if ((phoneNumberValid) || (firstNameValid && lastNameValid && (cityValid || zipValid)) {
    //Form Is Valid
}

每个变量代表一个布尔值,您应该在检查每个字段后设置它。

我认为仅使用 jQuery 验证插件无法完成如此复杂的检查。

phoneNumberValid, firstNameValid, lastNameValid, cityValid, zipValid;
if ((phoneNumberValid) || (firstNameValid && lastNameValid && (cityValid || zipValid)) {
    //Form Is Valid
}

Each variable represents a Boolean which you should set after checking each field.

I don't think such complex checking is doable with the jQuery validation plugin alone.

梦里泪两行 2024-12-06 17:03:12
 function formIsValid(){
   if(phoneNumberIsValid) { return true; }
   if(firstNameIsValid && lastNameIsValid) {
     return (cityIsValid || zipIsValid);
   }
   return false;
 }

如果您喜欢单行且不关心可读性:

return (phoneNumberIsValid || (firstNameIsValid && lastNameIsValid && (cityIsValid || zipIsValid)));

如果您有 条件模式匹配,如果你习惯的话,这样的东西可能会更具可读性

return match([phoneNumberValid, firstNameValid, lastNameValid, cityValid, zipValid],
[true, _], true,
[_, true, true, true, _], true,
[_, true, true, _, true], true,
_, false);
 function formIsValid(){
   if(phoneNumberIsValid) { return true; }
   if(firstNameIsValid && lastNameIsValid) {
     return (cityIsValid || zipIsValid);
   }
   return false;
 }

If you like one-liners and don't care about readability:

return (phoneNumberIsValid || (firstNameIsValid && lastNameIsValid && (cityIsValid || zipIsValid)));

If you have a plug-in for conditional pattern matching, something like this could be more readable if you are used to it

return match([phoneNumberValid, firstNameValid, lastNameValid, cityValid, zipValid],
[true, _], true,
[_, true, true, true, _], true,
[_, true, true, _, true], true,
_, false);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文