【问题标题】:Custom error message for jQuery validation on radio button group单选按钮组上 jQuery 验证的自定义错误消息
【发布时间】:2013-03-28 12:12:39
【问题描述】:

我正在使用以下代码进行组合框组验证,它显示 此字段是必需的。 作为错误消息。如何修改以下代码以自定义消息。提前致谢。

    $(document).ready(function() {    

    $('input[name="batches.batch"]').rules("add", "required");//works fine
    $('input[name="batches.batch"]').messages("error message1", "error message2");// no effect

});

我的html:

    <input name="batches.batch" type="radio" value="" />First <br />
    <input name="batches.batch" type="radio" value="" />Second<br />
    <input name="batches.batch" type="radio" value="" />Third<br />
    <input name="batches.batch" type="radio" value="" />Fourth<br />

我正在使用的库:

<script type="text/javascript" src="js/jquery-1.8.3.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.10.1.custom.min.js"></script>
<script type="text/javascript" src="js/custom/jquery.validate.min.js"></script>

【问题讨论】:

  • 你使用的是哪个,jquery-validate 还是 jquery-validation-engine?您的代码看起来像 jquery-validate。
  • @Barmar 我正在使用 jquery-validate。
  • 它不起作用,因为此插件不包含名为 .messages() 的此类方法。

标签: jquery html jquery-validate radio-button


【解决方案1】:

您的代码...

$('input[name="batches.batch"]').rules("add", "required");//works fine
$('input[name="batches.batch"]').messages("error message1", "error message2");// no effect

它不起作用,因为有 no documented method 称为 .messages()。方法必须由插件开发者创建才能可用。

相反,messages 进入您的 rules('add') 方法内部,就像这样...

$('document').ready(function() {

    $('#myform').validate();

    $('input[name="batches.batch"]').rules("add", {
        required: true,
        messages: {
            required: "my custom required message"
        }
    });

});

工作演示:http://jsfiddle.net/rDcDW/

上述方法非常适合动态添加规则,但是,如果您只需要workaround the name's with dots issue,只需将规则声明为正常,但在name 周围使用引号...

$(document).ready(function() {

    $('#myform').validate({ // initialize the plugin
        rules: {
            'batches.batch': {
                required: true
            }
        },
        messages: {
            'batches.batch': {
                required: "my custom required message"
            }
        }
    });

});

工作演示:http://jsfiddle.net/YZs3Y/

【讨论】:

  • [jsfiddle.net/YZs3Y/](jsfiddle.net/YZs3Y) 的演示运行良好。但发布的答案不起作用。非常感谢您提供演示代码。
  • @VisruthCV,我发布了两种完全不同的方法,它们都运行良好,正如每个 jsFiddle 所展示的那样。你能详细说明你在说什么吗?
【解决方案2】:
$("#formid").validate({
    rules: {
        batch: "required"
    },
    messages: {
        batch: { required: "Customized error message" }
    }
 });

【讨论】:

  • 它不工作。我已经更新了我的问题,请你再看一遍好吗!!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-12-27
  • 1970-01-01
  • 1970-01-01
  • 2011-10-30
  • 1970-01-01
  • 1970-01-01
  • 2018-02-08
相关资源
最近更新 更多