2013-03-27 67 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