I am comparing a username using a custom validation. I am checking if it’s the same as the old value or if it passes the regex it is acceptable but if it is not then throw an error. How do i get the UserID from the viewmodel if possible?
[EmailValidation]
public string Username{ get; set; }
public int UserID { get; set; }
public class EmailValidationAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
User user= User.getUserByID(UserID); //How to get UserID?
string username= value.ToString();
if (user.Username== username || IsValid(username))
{
return ValidationResult.Success;
}
else
{
return new ValidationResult("Error");
}
}
You can get UserID from
ObjectInstanceof ValidationContext. In your case it will be instance of your User class.If you want something more universal you can add property that specify property name and use reflection to get the value.