Entered Max value must be greater than Min. Right now my code displays error message when Max is same as Min (using compare). Is there validator that can be used to compare one input against another?
MyData.cs:
public class MyData
{
[Required]
public double Min { get; set; }
[Compare("Min", ErrorMessage = "checks for matching min value")]
public double Max { get; set; }
}
Form.razor:
<div >
<EditForm EditContext="@context">
<DataAnnotationsValidator />
<label for="Min">Min</label>
<input @bind=model.Min type="text">
<label for="Max">Max</label>
<input @bind=model.Max type="text">
<ValidationMessage For="@(() => model.Max)" />
</EditForm>
</div>
<div >
<button type="button" @onclick="() => Done()">Apply</button>
</div>
@code {
private MyData model = new MyData();
private EditContext context;
protected override void OnInitialized()
{
model = (MyData)(modalDialog?.ModalRequest.InData ?? new MyData());
context = new EditContext(model);
}
private void Done()
{
if (@model.Max < @model.Min)
{
context.Validate(); @*this displays error message*@
}
else
{
modalDialog?.Close(ModalResult.OK(model));
}
}
CodePudding user response:
To validate for greater than or less than against another property instead of a value using Data Annotations
you require to create a custom validation attribute as shown below:
GreaterThan attribute
// Custom attribute for validating greater than other property
public class GreaterThan : ValidationAttribute
{
private readonly string _comparisonProperty;
public GreaterThan(string comparisonProperty)
{
_comparisonProperty = comparisonProperty;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
ErrorMessage = ErrorMessageString;
var currentValue = (double)value; // cast to double same as property type
var property = validationContext.ObjectType.GetProperty(_comparisonProperty);
if (property == null)
throw new ArgumentException("Property with this name not found");
var comparisonValue = (double)property.GetValue(validationContext.ObjectInstance); // cast to property type
// comparison condition
if (currentValue < comparisonValue)
return new ValidationResult(ErrorMessage);
return ValidationResult.Success;
}
}
LessThan attribute
You can use the same code above to create for LessThan
attribute by changing the name and comparison condition to currentValue > comparisonValue
.
Below is an example on how to use Data Annotations
to validate your model and display validation errors in the form. It includes GreaterThan
custom validation attribute together with other common validation attribute.