是否需要jQuery Validate复选框?

我正在使用jQuery Validation插件来validation表单。

问题是我无法找到validation表单中是否选中了单个复选框的方法

HTML标记:

  

jQuery代码:

 rules: { terms: "required" }, messages:{ terms: "check the checbox" } 

任何帮助,将不胜感激。

HTML标记:

    

jQuery代码:

  rules: { terms: { required : true } }, messages:{ terms: { required : "check the checbox" } } 

jsfiddle: http : //jsfiddle.net/mZ6zJ/

您需要为复选框指定一个值。

  

也许你的复选框有css风格

 display: none 

替换为

 visibility: hidden; width: 0; 

它对我有帮助。

Checkbox Jqueryvalidation的示例

HTML

    
  • 使用方括号给复选框名称。
  • 为强制复选框提供价值。

Jquery代码

 $(document).ready(function() { $("#demo").validate({ rules: { 'terms[]': { required: true }, }, messages:{ 'terms[]': "check the checbox" } }); }); 

您需要将代码包装在文档就绪的jQuery方法和validation检查中:

 $().ready(function () { $('#formId').validate({ rules: { terms: "required" }, messages:{ terms: "check the checbox" } }) }) 

我希望这有帮助

我只是在C#中创建了自己的注释,并将其与我的jQueryvalidation相匹配。 现在我只是注释出现这个问题的任何复选框。 如果您不使用C#,则可以轻松地在要应用的元素上添加类。

 [System.AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] public class CheckboxRequired : ValidationAttribute, IClientValidatable { protected override ValidationResult IsValid(object value, ValidationContext validationContext) { if (value.GetType() != typeof(bool) || (bool)value == true) return ValidationResult.Success; return new ValidationResult("This checkbox must be checked."); } public IEnumerable GetClientValidationRules(ModelMetadata metadata, ControllerContext context) { var rule = new ModelClientValidationRule { ErrorMessage = "This checkbox must be checked.", ValidationType = "CheckboxRequired" }; yield return rule; } } 

在我的Validation.js

 jQuery.validator.addMethod("CheckboxRequired", function (value, element) { return (value != typeof undefined && value != false);}); jQuery.validator.addClassRules("CheckboxRequired", { CheckboxRequired: true});