[英]Partially validate model property using data annotation
我使用數據注釋對模型屬性設置了兩個驗證,如下所示:
[MinLength(8, ErrorMessage = "Password Requires at least one letter, one number and 8 characters long")]
[Required(ErrorMessage = "Password Required")]
public string Password { get; set; }
在某些特殊情況下,我需要部分驗證。 例如,我不想在用戶登錄時檢查最小長度,而僅在注冊時檢查。
任何人都知道如何實現這一目標嗎?
就像默認的asp.net-mvc實現一樣,使用不同的ViewModel進行注冊和登錄。
您將獲得3個類:模型本身,登錄類和注冊類。 具有密碼長度驗證的唯一類應該是Model本身,而不是視圖Models。 然后,使用控制器,您應該將其從ViewModel填充到模型中(當執行Posts時)或將模型填充到ViewModel中(當執行Gets時)
登錄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; }
}
所有默認MVC的Register ViewModel和Model本身的用法示例
[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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.