繁体   English   中英

使用数据注释部分验证模型属性

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM