2013-03-27 69 views
1

我使用下面的代码进行组合框组验证,它显示此字段是必需的。作为错误消息,请输入。我如何修改下面的代码来自定义消息。提前致谢。单选按钮组上的jQuery验证自定义错误消息

$(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> 
+0

?你的代码看起来像jquery-validate。 – Barmar 2013-03-27 08:15:04

+0

@Barmar我正在使用jquery-validate。 – Visruth 2013-03-27 08:47:39

+0

它不工作,因为这个插件不包含名为'.messages()'的这种方法。 – Sparky 2013-03-27 15:00:18

回答

3

你的代码...

$('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" 
      } 
     } 
    }); 

}); 

工作演示:你使用的是哪个,jQuery的验证或jQuery的验证引擎http://jsfiddle.net/YZs3Y/

+0

演示在[http://jsfiddle.net/YZs3Y/](http://jsfiddle.net/YZs3Y/)工作正常。但发布的答案不起作用。非常感谢你的演示代码。 – Visruth 2013-03-28 04:06:46

+0

@VisruthCV,我发布了两个完全不同的方法,他们都工作正常,由每个jsFiddle演示。你能详细说说你在说什么吗? – Sparky 2013-03-28 04:22:11

1
$("#formid").validate({ 
    rules: { 
     batch: "required" 
    }, 
    messages: { 
     batch: { required: "Customized error message" } 
    } 
}); 
+0

这不起作用。我已经更新了我的问题,请你再看一遍吧! – Visruth 2013-03-27 09:38:50