jQuery验证插件,如何在自定义方法中添加多个自定义消息 [英] jquery validation plugin, how to add multiple custom messages in custom method

查看:112
本文介绍了jQuery验证插件,如何在自定义方法中添加多个自定义消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 jquery验证插件

我使用 addmethod 添加了一个自定义方法,而该方法又调用了另一种方法检查有效的UK telephone number

I added a custom method using addmethod which in turn calls another method to check for valid UK telephone number

这是我的代码(简体):

here is my code (simplified):

html

<form id="myform">
  <label for="field">Required, telephone: </label>
  <input class="required" id="field" name="field" />
  <br/>
  <input type="submit" value="Submit" />
</form>

jquery

$(document).ready(function(){
    $("#myform").validate({
        rules:{
            field:{
                required:true;
                UKTelNumber:true
            }
        }       
    });
});

jQuery.validator.addMethod("UKTelNumber", function(value,element) {

    if (!checkUKTelephone (value)) {
        alert (telNumberErrors[telNumberErrorNo]);
        return false;
    }
    else {
        return true
    }       
},jQuery.validator.format(telNumberErrors[telNumberErrorNo]));

函数 checkUKTelephone 根据错误类型设置var telNumberErrorNo 的值. 所有错误消息都位于数组 telNumberErrors 中.

The function checkUKTelephone sets the value of var telNumberErrorNo according to the type of error. All the error messages are there in an array telNumberErrors.

现在我的要求是如何显示那些现在正在发出警报的错误消息.

Now my requirement is that how to show those error messages that is being alerted now.

jQuery.validator.format(telNumberErrors[telNumberErrorNo])作为 addMethod 的消息(第三个选项)传递不是帮助.

passing jQuery.validator.format(telNumberErrors[telNumberErrorNo]) as message (third option) of addMethod is not helping.

我还尝试仅传递此telNumberErrors[telNumberErrorNo],但每次仅显示一条消息,即telNumberErrors[0]

I also tried passing only this telNumberErrors[telNumberErrorNo] but its showing only one message every time i.e message contained in telNumberErrors[0]

请帮助我

预先感谢

推荐答案

我已经解决了我的问题,所以我想回答自己的问题,这可能会对其他人有所帮助

Well I got the solution to my question so I thought to answer my own question that it may help others

只需创建一个函数并返回被警告的错误

just create a function and return the error which is being alerted

var dispError = function(){
    return telNumberErrors[telNumberErrorNo];
}

,然后将该函数作为第三个参数传递给 addMethod

and then pass that function as the third argument to addMethod

jQuery.validator.addMethod("UKTelNumber", function(value,element) {    
    if (!checkUKTelephone (value)) {
        return false;
    }
    else {
        return true
    }       
},dispError);

然后调用validate方法

then call the validate method

$(document).ready(function(){
    $("#myform").validate({
        rules:{
            field:{
                required:true;
                UKTelNumber:true
            }
        }       
    });
});

这篇关于jQuery验证插件,如何在自定义方法中添加多个自定义消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆