我正在写asp.net核心,形式我有字符串字段PESEL
(它是波兰的一些ID号)和布尔字段NoPesel
。 Pesel
仅在未选中字段NoPesel
时进行验证。
现在我要添加新功能:如果用户是登录/授权,则即使取消选中NoPesel
也会关闭验证。
我不知道该怎么做。我应该尝试通过反思或某些背景来做到这一点吗?有人知道怎么做吗?
public sealed class PeselValidator : ValidationAttribute
{
// private const string DefaultErrorMessage = "Nie poprawny numer pesel";
public string NoPesel { get; set; }
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (PeselRequired(validationContext.ObjectInstance, NoPesel))
{
return ValidationResult.Success;
}
if ((value == null) || (!ValidatePesel(value.ToString())) )
return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
return ValidationResult.Success;
}
public override string FormatErrorMessage(string name)
{
return base.FormatErrorMessage(ErrorMessageResourceName);
}
public void AddValidation(ClientModelValidationContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
ErrorMessage = FormatErrorMessage(context.ModelMetadata.GetDisplayName());
}
private bool PeselRequired(object objectInstance, string NoPesel)
{
var propertyInfo = objectInstance.GetType().GetProperty(NoPesel);
var x = propertyInfo.GetValue(objectInstance, null);
return (bool)x;
}
public static bool ValidatePesel(string szPesel)
{
//some logic checking PESEL SUM
return true;
}
}