我已经创建了以下自定义属性来帮助我验证必需的复选框字段:
public class CheckboxRequired : ValidationAttribute, IClientValidatable
{
public CheckboxRequired()
: base("required") { }
public override bool IsValid(object value)
{
return (bool)value == true;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
ModelClientValidationRule rule = new ModelClientValidationRule();
rule.ErrorMessage = FormatErrorMessage(metadata.GetDisplayName());
rule.ValidationType = "mandatory";
yield return rule;
}
}但是,我试图让它触发客户端,而不是在调用我的ActionResult (if (ModelState.IsValid))时触发
当我调用我的ActionResult时,验证确实起作用了,但我更希望在进行到这一步之前进行验证。
我需要做哪些修改才能让验证在客户端发挥作用?
谢谢
发布于 2011-06-22 17:32:09
为了实现客户端,您可以添加例如一个jQuery验证器方法和一个不显眼的适配器(简单示例):
// Checkbox Validation
jQuery.validator.addMethod("checkrequired", function (value, element)
{
var checked = false;
checked = $(element).is(':checked');
return checked;
}, '');
jQuery.validator.unobtrusive.adapters.addBool("mandatory", "checkrequired");我希望它能帮上忙。
发布于 2012-01-23 01:03:02
旧的好的Regex怎么样?
[RegularExpression("^(true|True)$", ErrorMessage="Required...")]
public bool AgreeWithTos { get; set; }同时接受"true“和”True“作为javascript和.NET格式的布尔值。
https://stackoverflow.com/questions/6437315
复制相似问题