I have a custom validation attached to a property. The validation works as expected except that when it shows that the field needs to be fixed, the error does not immediately clear when the issue is fixed like what the build in validations does. The error does not stop me from submitting my form but it seems when the error is displayed it then revalidates on the button submit click. How can I make it behave like what the default validations do i.e. when the field is incorrect it shows the error and when the field is corrected the error immediately goes away?
below is the implementation of the validation
public class RequireGreaterThanZeroAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
try
{
var objectValue = value.GetType().ToString().ToUpper() == "SYSTEM.DECIMAL" ? Convert.ToDecimal(value) : (int)value;
if (objectValue > 0)
return ValidationResult.Success;
else
return new ValidationResult($"{validationContext.DisplayName} must be greater than zero.");
}
catch
{
return new ValidationResult($"{validationContext.DisplayName} must be greater than zero.");
}
}
}
Below is the markup where the property is being used
<div class="col-lg-3">
<div class="form-group">
<label>Amount</label>
<InputNumber @bind-Value="@Transaction.Amount" type="text" class="form-control required"/>
</div>
</div>
and the Model property is defined as
[RequireGreaterThanZero]
public decimal Amount { get; set; } = 0.00M;
The Submit button is like below
<div class="row">
<div class="col-lg-6">
<div class="form-group">
<button type="submit" style="width:100%" class="btn btn-sm btn-primary @BuyClass @SellClass @UpdateClass @ReverseClass" data-toggle="tooltip" data-placement="top" title="Save"><i class="fa fa-save"></i> @ButtonText</button>
</div>
</div>
</div>
While testing the solution provided by @MrCakaShaunCurtis, what i have noted is that this issue has something to do with the DataAnnotationsValidator when you use
<DataAnnotationsValidator />
instead of
<ValidationMessage For="() => Transaction.Amount" />
This is when the message doesnt go away. With
<ValidationMessage For="() => Transaction.Amount" />
the message behaves correctly.
@MrCakaShaunCurtis , can you try using the
<DataAnnotationsValidator />
instead of the validation For and see if this also happens on your side?
Also i notice this seems to be a long oustanding issue, just stumbled on another related issue on
How to reset custom validation errors when using editform in blazor razor page