使用OR的jqueryvalidation规则可能吗?

时间:2014-03-18 17:59:38

标签: jquery-mobile jquery-validate

我正在创建一个小型jquery移动项目,并决定使用jqueryvalidation http://jqueryvalidation.org/进行表单验证。我有一个弹出框,用户输入一个号码,可以是他们的电话或电子邮件(不幸的是,由于数据库,这必须保持这样)所以我想使用验证来说明该字段必须包含电子邮件:数字:

你知道这是否可能吗?还是一个工作区?在这种情况下,使用依赖:将无法正常工作,因为没有条件可以在每个数据库上运行(主要电话/电子邮件不会一直被填充)。

                      <form id='addNumber' action ='' method='post' data-ajax='false'>
                        <div class="ui-field-contain">
                        <label for="phoneType">Type</label>
                            <select name="phoneType" id="phoneType" data-native-menu="false">
                                <?php echo $phoneInnerOptions; ?>
                            </select>
                        </div>
                        <div class="ui-field-contain">
                            <label for="phoneNumber">Number</label>
                            <input type="text" name="phoneNumber" id="phoneNumber" value="">
                        </div> 
                        <div class="ui-field-contain">
                            <label for="primary">Primary Contact</label>
                            <select name="primary" id="primary" data-native-menu="false" >
                                <option value="1">Primary Phone</option>
                                <option value="2">Primary Email</option>
                                <option value="3"></option>
                            </select>
                        </div> 
                        <div class='ui-grid-a'>

                            <div class='ui-block-a'><input type='submit' value='Update' class='ui-btn ui-btn-inline' data-transition='pop' /></div>
                            <div class='ui-block-b'><a href='#' id="addNumberReset" class='ui-btn' data-rel='back' data-transition='pop'>Cancel</a></div>
                        </div>
                    </form>

目前的验证:

 $().ready(function() {     
                    // validate add number form
                 $("#addNumber").validate({
                        errorPlacement: function(error, element) {
                            error.insertAfter(element.parent()); // <- make sure the error message appears after parent element (after textbox!)
                        },
                        rules: {
                            phoneNumber: "required",
                        },
                        messages: {
                            phoneNumber: "Please enter a valid phone or email",
                        }
                    }); //end validate
                });// end function

对此任何帮助或建议将不胜感激:)

2 个答案:

答案 0 :(得分:1)

在这种情况下,您最好的选择是使用the .addMethod() method编写自己的规则。


来自docs的简单示例:

jQuery.validator.addMethod("myrule", function(value, element) {
    // return 'true' to pass validation or return 'false' to fail validation
    return this.optional(element) || /^http:\/\/mycorporatedomain.com/.test(value);
}, "Please specify the correct domain for your documents");

标记声明此示例规则:

rules: {
    myfield: {
        myrule: true  // only passes validation if "http://mycorporatedomain.com" is entered
    }
}

使用参数的文档中的简单示例:

jQuery.validator.addMethod("myrule", function(value, element, params) {
    // return 'true' to pass validation or return 'false' to fail validation
    return this.optional(element) || value == params[0] + params[1];
}, jQuery.validator.format("Please enter the correct value for {0} + {1}"));

标记声明此示例规则:

rules: {
    myfield: {
        myrule: [5,20] // only passes validation if '25' is entered
    }
}

两个示例中的

this.optional(element)使字段条目“可选”。如果您还想要字段required,只需删除此部分。

您可以浏览the additional-methods.js file以查看此方法的数十个真实工作示例。

答案 1 :(得分:0)

继承了我最终使用的代码,其他任何人都可能需要它...感谢这一个闪亮的帮助

//creating the new rule
//Matches UK landline + mobile, accepting only 01-3 for landline or 07 for mobile to    exclude many premium numbers
jQuery.validator.addMethod('phonesUK', function(phone_number, element) {
phone_number = phone_number.replace(/\(|\)|\s+|-/g,'');
return this.optional(element) || phone_number.length > 9 &&
phone_number.match(/^(?:(?:(?:00\s?|\+)44\s?|0)(?:1\d{8,9}|[23]\d{9}|7(?:[45789]\d{8}|624\d{6})))$/);
});

//use phonesUK or standard email
jQuery.validator.addMethod("phoneOrEmail", function(value, element) {
return this.optional(element) ||
($.validator.methods["phonesUK"].call(this, value, element)) ||
($.validator.methods["email"].call(this, value, element));
}, "Please enter a valid phone number or email address");

//apply it to my page
    $(document).on("pagecreate", function () {      
                    // validate new number form
                    $("#addNumber").validate({
                        errorPlacement: function(error, element) {
                            error.insertAfter(element.parent()); // <- make sure the error message appears after parent element (after textbox!)
                        },
                        rules: {

                            phoneNumber: 
                                {
                                    phoneOrEmail: true,
                                    required: true,
                                }

                        },
                        messages: {
                            phoneNumber: "Please enter a valid phone number or email address",
                        },

                        //check if valid - post if is
                        submitHandler: function(form) {
                            $('#PopUpAddNumber').popup('close');
                            $.post("customer_AddNewNumber.php", $("#addNumber").serialize(),  function(response)
                            {
                                 LoadCustomerNumber();
                            });

                        }
                    }); //end validate
                                        //reset form after validate
                    $('#addNumberReset').click(function () {
                    $('#addNumber').validate().resetForm();
                    });
                }); // end function