Son*_*u K 35 validation asp.net-mvc model
我有一个模型类,如:
public class Student
{
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
[Display(Name = "Enrollment Date")]
public DateTime EnrollmentDate { get; set; }
[Required]
[Display(Name = "Is Active")]
public bool IsActive { get; set; }
public virtual ICollection<Enrollment> Enrollments { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
在这里,我已经创建了一个Boolean
属性IsActive
与Required
属性,但问题是,我的看法是不执行所需的验证此属性?我想用a绑定此属性CheckBox
并检查是否CheckBox
已选中此选项并运行验证(如果不是).
对此有何解决方案?
Son*_*u K 66
[Display(Name = "Is Active")]
[Range(typeof(bool), "true", "true", ErrorMessage="The field Is Active must be checked.")]
public bool IsActive { get; set; }
Run Code Online (Sandbox Code Playgroud)
小智 26
感谢上面的解决方案,这使我处于正确的方向,但对我来说它并没有很好地工作.我需要将以下脚本添加到扩展jquery验证器的页面以使上述解决方案工作.想要分享这个,如果有人遇到类似的问题.
<script>
// extend jquery range validator to work for required checkboxes
var defaultRangeValidator = $.validator.methods.range;
$.validator.methods.range = function(value, element, param) {
if(element.type === 'checkbox') {
// if it's a checkbox return true if it is checked
return element.checked;
} else {
// otherwise run the default validation function
return defaultRangeValidator.call(this, value, element, param);
}
}
</script>
Run Code Online (Sandbox Code Playgroud)
让我补充一点Sonu K
发布
如果您在(<input type="checkbox" required/>
)上使用HTML验证,则可能最终会干扰您的JavaScript,从而阻止您从模型中提交空的必填字段集
最后,如果您不希望Is Active
在进行迁移时将其添加到数据库中(代码优先),只需添加[NotMapped]
完整代码
[NotMapped]
[Display(Name = "Is Active")]
[Range(typeof(bool), "true", "true", ErrorMessage="The field Is Active must be checked.")]
public bool IsActive { get; set; }
Run Code Online (Sandbox Code Playgroud)
因为尽管它会在浏览器中显示取消选中状态,但在MVC中默认将其设置为true,因此验证可能无法按您期望的那样工作,这就是为什么必须添加此javascript代码来完善验证的原因。
<script>
// extend jquery range validator to work for required checkboxes
var defaultRangeValidator = $.validator.methods.range;
$.validator.methods.range = function(value, element, param) {
if(element.type === 'checkbox') {
// if it's a checkbox return true if it is checked
return element.checked;
} else {
// otherwise run the default validation function
return defaultRangeValidator.call(this, value, element, param);
}
}
</script>
Run Code Online (Sandbox Code Playgroud)
享受编码
归档时间: |
|
查看次数: |
21804 次 |
最近记录: |