Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用数据注释部分验证模型属性_C#_Asp.net Mvc_Data Annotations - Fatal编程技术网

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

C# 使用数据注释部分验证模型属性,c#,asp.net-mvc,data-annotations,C#,Asp.net Mvc,Data Annotations,我使用数据注释对模型属性设置了两个验证,如下所示: [MinLength(8, ErrorMessage = "Password Requires at least one letter, one number and 8 characters long")] [Required(ErrorMessage = "Password Required")] public string Password { get; set; } 我想在一些特殊情况下进行部分验证。例如,我不想在用户登录时检查

我使用数据注释对模型属性设置了两个验证,如下所示:

 [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实现一样

您将得到3个类:模型本身、登录类和注册类。具有密码长度验证的唯一类应该是模型本身,而不是视图模型。然后,使用控制器,您应该从ViewModel填充到模型(当执行POST时)或从模型填充到ViewModel(当执行GET时)

登录视图模型示例(取自默认MVC代码)

和注册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; }
}
[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);
    }
注册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; }
}
[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);
    }
[HttpPost]
[异名]
[ValidateAntiForgeryToken]
公共异步任务);
返回重定向到操作(“索引”、“主页”);
}
加法器(结果);
}
//如果我们走到这一步,有些东西失败了,重新显示形式
返回视图(模型);
}

然后使用两种视图模型,一种用于登录,另一种用于注册(由于注册视图应具有“确认密码”字段,因此它们应该有所不同),请查看FluentValidation以解决您的问题