简体   繁体   English

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

[英]Partially validate model property using data annotation

I Have set two validation on model property using Data Annotation, like below: 我使用数据注释对模型属性设置了两个验证,如下所示:

 [MinLength(8, ErrorMessage = "Password Requires at least one letter, one number and 8 characters long")]
 [Required(ErrorMessage = "Password Required")]
 public string Password { get; set; }

I want partial validation in some special cases. 在某些特殊情况下,我需要部分验证。 For eg i dont want to check minimum length when user login , but only at a time of register. 例如,我不想在用户登录时检查最小长度,而仅在注册时检查。

Can any body know how to achieve this? 任何人都知道如何实现这一目标吗?

Use different ViewModels for Registration and Login, just like the default asp.net-mvc implementation does. 就像默认的asp.net-mvc实现一样,使用不同的ViewModel进行注册和登录。

You'll end up with 3 classes: Your Model itself, A login class and a registration class. 您将获得3个类:模型本身,登录类和注册类。 The only class with the password lenght validation should be the Model itself, not the view Models. 具有密码长度验证的唯一类应该是Model本身,而不是视图Models。 Using your controller your should then populate from the ViewModel into the Model(When doing Posts) or from the Model into the ViewModel (When doing Gets) 然后,使用控制器,您应该将其从ViewModel填充到模型中(当执行Posts时)或将模型填充到ViewModel中(当执行Gets时)

Example of a Login ViewModel (Taken from the default MVC code) 登录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; }
}

And a Register ViewModel, also from the default MVC 还有一个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; }
}

Example of usage of the Register ViewModel and the Model itself, all default MVC 所有默认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