使用数据注释部分验证模型属性
Posted
技术标签:
【中文标题】使用数据注释部分验证模型属性【英文标题】:Partially validate model property using data annotation 【发布时间】:2015-12-14 02:30:06 【问题描述】:我已经使用数据注释对模型属性设置了两个验证,如下所示:
[MinLength(8, ErrorMessage = "Password Requires at least one letter, one number and 8 characters long")]
[Required(ErrorMessage = "Password Required")]
public string Password get; set;
我希望在某些特殊情况下进行部分验证。例如,我不想在用户登录时检查最小长度,而只是在注册时检查。
任何机构都知道如何做到这一点吗?
【问题讨论】:
然后使用 2 个视图模型,一个用于登录,一个用于注册(它们应该是不同的,因为注册视图应该有一个确认密码字段) 请查看 FluentValidation 这可以解决您的问题fluentvalidation.codeplex.com/wikipage?title=mvc 【参考方案1】:使用不同的 ViewModel 进行注册和登录,就像默认的 asp.net-mvc 实现一样。
您最终会得到 3 个类:您的模型本身、登录类和注册类。唯一具有密码长度验证的类应该是模型本身,而不是视图模型。然后使用您的控制器,您应该从 ViewModel 填充到模型中(当做 Posts 时)或从 Model 填充到 ViewModel 中(当做 Gets 时)
Login ViewModel 示例(取自默认 MVC 代码)
public class LoginViewModel
[Required]
[Display(Name = "Email")]
[EmailAddress]
public string Email get; set;
[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password get; set;
[Display(Name = "Remember me?")]
public bool RememberMe get; set;
还有一个Register ViewModel,同样来自默认的MVC
public class RegisterViewModel
[Required]
[EmailAddress]
[Display(Name = "Email")]
public string Email get; set;
[Required]
[StringLength(100, ErrorMessage = "The 0 must be at least 2 characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password get; set;
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword get; set;
Register ViewModel和Model本身的使用示例,全部默认MVC
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
if (ModelState.IsValid)
var user = new ApplicationUser UserName = model.Email, Email = model.Email ;
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
// For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
// Send an email with this link
// string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
// var callbackUrl = Url.Action("ConfirmEmail", "Account", new userId = user.Id, code = code , protocol: Request.Url.Scheme);
// await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");
return RedirectToAction("Index", "Home");
AddErrors(result);
// If we got this far, something failed, redisplay form
return View(model);
【讨论】:
以上是关于使用数据注释部分验证模型属性的主要内容,如果未能解决你的问题,请参考以下文章