我写了一个自定义属性:

public class UniqueNationalId : ValidationAttribute
 {
  private readonly UserService _userService;

public UniqueNationalId()
{
    _userService = new UserService();
}

protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
    if (_userService.IsNationalIdExist(value.ToString()))
        return new ValidationResult("National code is available in the system");
    return null;
}


我使用IsNationalIdExist方法:

    public bool IsNationalIdExist(string nationalId)
    {
        var validateName = _user.FirstOrDefault
                            (x => x.UserId == nationalId);
        if (validateName != null)
        {
            return true;
        }
        else
        {
            return false;
        }
       // return false;
    }


类模型:

[IsValidNationalId]
    [UniqueNationalId]
    public string NationalId { get; set; }


错误给出以下内容

在UniqueNationalId.IsValid(对象值,ValidationContextvalidationContext)

我应该进行哪些更改?

最佳答案

如果验证成功,则应返回ValidationResult.Success,否则返回错误消息,即

protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
    if (_userService.IsNationalIdExist(value.ToString()))
        return ValidationResult.Success;
    else
        return new ValidationResult("National code is not available in the system");
}

08-26 00:45