i'm writing in asp.net core, in form i have string field PESEL
(it is some ID number in Poland) and boolean field NoPesel
. Pesel
is validating only when field NoPesel
is unchecked.
Now i want to add new functionality: If user is SignIn/authorize then turn off validation even if NoPesel
is unchecked.
And i have no idea how to do this. Should i try to do it by reflecion, or some context? Did someone know how to do this?
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;
}
}
Aucun commentaire:
Enregistrer un commentaire