gpt4 book ai didi

c# - UniqueNationalId.IsValid(对象值,ValidationContext validationContext)

转载 作者:行者123 更新时间:2023-11-30 18:11:35 25 4
gpt4 key购买 nike

我写了一个自定义属性:

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(对象值,ValidationContext validationContext)

我应该做哪些改变????

最佳答案

如果验证成功,您应该返回 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");
}

关于c# - UniqueNationalId.IsValid(对象值,ValidationContext validationContext),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57664728/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com