Try typing a date in the End input that is earlier than the Start date, and press Submit.
Or, use the Up and Down arrows to change the value of either input.
Submit
@code {
private DateRangeModel dateRange { get; set; } = new DateRangeModel()
{
StartDate = DateTime.Today,
EndDate = DateTime.Today.AddDays(5)
};
async void HandleValidSubmit()
{
Console.WriteLine("OnValidSubmit");
}
// A custom validation attribute is used to show an error message to the user
// if they type an end date that is before the start date in the input
public class CompareDateAttribute : ValidationAttribute
{
public string compareToDateTimeProperty;
public CompareDateAttribute(string compareToPropertyName)
{
this.compareToDateTimeProperty = compareToPropertyName;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var validationObject = validationContext.ObjectInstance;
PropertyInfo propertyInfo = validationObject.GetType().GetProperty(compareToDateTimeProperty);
var currentValue = (DateTime?)value;
var compareToValue = (DateTime?)propertyInfo?.GetValue(validationObject);
return currentValue < compareToValue ? ValidationResult.Success : new ValidationResult(ErrorMessage, new[] { validationContext.MemberName });
}
}
public class DateRangeModel
{
[Required]
[Range(typeof(DateTime), "1/1/2019", "1/12/2025",
ErrorMessage = "Value for {0} must be between {1:dd MMM yyyy} and {2:dd MMM yyyy}")]
// custom validation attribute to ensure start date is before the end date
[CompareDate(nameof(EndDate), ErrorMessage = "The Start date must be before the End date.")]
public DateTime? StartDate { get; set; }
[Required]
[Range(typeof(DateTime), "1/1/2019", "1/12/2025",
ErrorMessage = "Value for {0} must be between {1:dd MMM yyyy} and {2:dd MMM yyyy}")]
public DateTime? EndDate { get; set; }
public DateRangeModel()
{
}
}
}
````
### DropDownList
The DropDownList always has an item selected - the first item from its data source, the item corresponding to the `Value`, or the item created from the `DefaultText` the developer provides (which has the default value for the type of the Value field - for example, `0` for an `int` and `null` for an `int?` or `string`).
This means that for required field validation to work, the current item must have a `null` value. Alternatively, if you cannot alter the dropdownlist item model you already have, you can use range validation and set a value for the default item that is outside of the range of actual values.
>caption How to validate a dropdownlist
````CSHTML
@using System.ComponentModel.DataAnnotations
@* This Using is for the model class attributes only *@
@* The Id parameter is not mandatory for validation, ut just shows better forms integration *@