1

我对密码进行了比较验证 - 确认密码字段以及服务器验证以检查密码是否符合最少字符数。

看法:

@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);
        }
    }

执行服务器验证时,警告消息会正确显示,之后比较验证将不再起作用。任何想法?

4

2 回答 2

1

根据我们的评论,我认为实际上最好的解决方案是编写自己的 DataAnnotation。

就像是[CompareIf("password", ErrorMessage = "Error comparing password and password confirm values")]

您的 DataAnnotation 代码必须检查密码是否为空且有效,然后比较这两个值。

于 2012-09-27T10:31:25.930 回答
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; }

这将允许仅在条件为真时进行比较。

于 2021-06-22T15:55:55.480 回答