我对密码进行了比较验证 - 确认密码字段以及服务器验证,以检查密码是否符合最少的字符数。
查看:
@Html.PasswordFor(model => model.password)
@Html.PasswordFor(model => model.repeatPassword)
型号:
public class Model_Clerk
{
public int clerkID { get; set; }
public string password { get; set; }
[Compare("password", ErrorMessage = "Error comparing password and password confirm values")]
public string repeatPassword { get; set; }
}
控制器动作方法:
public ActionResult SaveClerk(Model_Clerk model)
{
//Password minimum lenght
if (!string.IsNullOrEmpty(model.password) && model.password.Trim().Length < 5)
{
ModelState.AddModelError(model.password, "Password must be at least 5 characters long");
}
if (ModelState.IsValid)
{
//Save logic here...
}
else
{
return PartialView("EditClerks", model);
}
}
执行服务器验证时,警告消息会正确显示,之后比较验证将不再起作用。有什么想法吗?
答案 0 :(得分:1)
从我们的评论中,我认为实际上最好的解决方案是编写自己的DataAnnotation。
像[CompareIf("password", ErrorMessage = "Error comparing password and password confirm values")]
您的DataAnnotation代码必须检查密码是否为空且有效,然后比较这两个值。
答案 1 :(得分:0)
今天遇到了这个问题并编写了一个 CompareIf
自定义属性。它几乎与 RequiredIf
(covered here) 相同,但继承了 CompareAttribute
并接受 otherProperty
作为第三个参数。
using System.ComponentModel.DataAnnotations;
public class CompareIfAttribute : CompareAttribute
{
private readonly string _dependentProperty;
private readonly object _targetValue;
public CompareIfAttribute(string dependentProperty, object targetValue, string otherProperty) : base(otherProperty)
{
_dependentProperty = dependentProperty;
_targetValue = targetValue;
}
/// <summary>
/// Returns if the given validation result is valid. It checks if the RequiredIfAttribute needs to be validated
/// </summary>
/// <param name="value">Value of the control</param>
/// <param name="validationContext">Validation context</param>
/// <returns></returns>
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var field = validationContext.ObjectType.GetProperty(_dependentProperty);
if (field != null)
{
var dependentValue = field.GetValue(validationContext.ObjectInstance, null);
if (dependentValue == null && _targetValue == null || dependentValue?.ToString() == _targetValue?.ToString())
{
var test = base.IsValid(value, validationContext);
if (test != ValidationResult.Success)
{
return test;
}
}
return ValidationResult.Success;
}
throw new ValidationException($"CompareIf Dependant Property {_dependentProperty} does not exist");
}
}
前两个参数是依赖属性和目标值,第三个是要比较的属性。用法:
public bool CandidateHasNoLegalMiddleName { get; set; }
public string CandidateMiddle { get; set; }
[CompareIf(nameof(CandidateHasNoLegalMiddleName), false, nameof(CandidateMiddle)]
public string ConfirmMiddle { get; set; }
这将允许仅在条件为真时进行比较。