我需要知道如何在asp.net MVC中实现可选验证。就像我的 LoginViewModel 一样,我有3个字段(1)电子邮件,(2)用户名(3)密码查看用户可以在同一输入框中输入电子邮件或密码,如果我在电子邮件和用户名字段中输入 [必需] ,则不会工作。所以,请告诉我如何在这种情况下处理它。
由于 Sohaib Javed
答案 0 :(得分:1)
尽管我不同意您应该为password
和email address
设置一个输入字段,但您可以在控制器中为传入视图执行验证模型:
public ActionResult Index(LoginViewModel requestResponseModel)
{
// Has an email or password been entered?
if (string.IsNullOrWhiteSpace(requestResponseModel.EmailOrPassword))
{
this.ModelState.AddModelError("EmailOrPassword", "Please enter an email or a password");
}
else
{
try
{
// Is the input a valid email address?
var addr = new System.Net.Mail.MailAddress(email);
return addr.Address == email;
}
catch
{
// Not valid email, is it a valid password?
if (System.Text.regularExpressions.Regex.IsMatch(requestResponseModel.EmailOrPassword, "^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^\da-zA-Z]).{8,15}$"))
{
this.ModelState.AddModelError("EmailOrPassword", "Value entered is not a valid email address or password");
}
}
}
// Did it pass validation?
if (this.ModelState.IsValid())
{
// Register the user here...
}
return View(requestResponseModel);
}
您还可以在视图模型的Validate()
IValidatableObject
方法中实现相同的代码。您可以在模型上使用[Required]
并在控制器中使用此验证。