[英]How can I create an asp.net MVC custom model validation that is working with 2 or more fields
I need following attributes: 我需要以下属性:
1.For example: i have 2 field. 1.例如:我有2个字段。 first is checkbox, second is textbox.
第一个是复选框,第二个是文本框。 If first control checked.
如果先检查控件。 second field must be
Required
attribute. 第二个字段必须是
Required
属性。 first control unchecked. 第一控件未选中。 second control not required.
不需要第二个控件。
[Required]
public boolean showHeader{get;set;}
[IFRequired("showHeader",true)]
public string HeaderText{get;set;}
2.For example: i have 2 field. 2.例如:我有2个字段。 new password, confirmation password.
新密码,确认密码。 Attribute must check this 2 field are equal.
属性必须检查这2个字段是否相等。
[Required]
public string newPassword{get;set;}
[Expression("newPassword",ExpressionAttributeEnum.Equils)]
public string confirmPassword{get;set;}
How to create above attributes? 如何创建以上属性?
This is not possible using attributes. 使用属性是不可能的。
however you can do it quite easy in your action. 但是您可以轻松地进行操作。
public ActionResult Create(FormCollection collection) {
///do your checks here which you cant do using attributes
ModelState.AddModelError("fieldname", "yourErrorMessage");
if (ModelState.IsValid) {
////.........
}
return View();
}
For point 2 if you're using MVC3 use the Compare attribute 对于第2点,如果您使用的是MVC3,请使用Compare属性
[Required] public string newPassword{get;set;} [必需]公用字符串newPassword {get; set;}
[Compare(] public string confirmPassword{get;set;} [Compare(]公共字符串ConfirmPassword {get; set;}
Have a look at this SO question and answer for the first part 看一下第一部分的SO问答
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.