I'm trying to resolve a problem I found while trying to do a custom validation attribute on my daughter's dog store using blazor.
Basically I have a property as follow:
[Test]
public int? PetAge { get; set; }
As you can see, I'm going to create a custom attribute called "Test", so I created a new class as follow:
public class Test : ValidationAttribute
{
protected override ValidationResult? IsValid(object? value, ValidationContext validationContext)
{
return new ValidationResult("niet! niet!");
}
}
and my understanding is that I can return a new ValidationResult with a string message or if everything goes fine, I can return ValidationResult.Success. In my example, it should always return a problem, as we did not provide any other logic than always returning a validationresult.
When running this code, it simply does not return anything, no error displayed on the form. Now what I did notice is that if I use the other version of the IsValid method, it works, the only problem is that I would like to send a custom message back and not just a true/false result. The one working is as follow:
public override bool IsValid(object? value)
{
return false;
}
But in that case, I have to provide the error message in the parameter like this:
[Test(ErrorMessage("this is not ok!")]
public int? PetAge { get; set; }
As these parameters must be constants, it was an awesome idea not only to be able to display a custom-built message as an error and/or have access to the context, etc...
am I doing something wrong on my Blazor app? any help will be appreciated!
I noticed this too, try the following
public class Test : ValidationAttribute
{
protected override ValidationResult? IsValid(object? value, ValidationContext validationContext)
{
return new ValidationResult("niet! niet!", new[] { validationContext.MemberName });
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With