Reputation: 14155
I want to enter date time as string inside textbox. Actually there are two input fields
Both should be in format like 00:00 so I can enter
From time 00:00
To time 23:59
how can validate user input in asp.net mvc viewmodel using annotations so I can restrict users input from 00:00
as min value and 23:59
as max value?
Upvotes: 1
Views: 234
Reputation: 1779
Using regular expression, you can validate your model, and client side validation also work with this like
[RegularExpression(@"^(0[1-9]|1[0-2]):[0-5][0-9] (am|pm|AM|PM)$", ErrorMessage = "Error message")]
public string FromTime {get;set;}
Upvotes: 0
Reputation: 6850
You could create a custom attribute that you can decorate your property with.
namespace JensB.Tools.CustomAttributes
{
public class IsDateOk: ValidationAttribute
{
public override bool IsValid(object value)
{
if (value == null) return false;
if (value.GetType() != typeof(DateTime)) throw new InvalidOperationException("can only be used on DateTime properties.");
bool isValid = // do validation here
return isValid;
}
}
}
You can then decorate your property like this:
[IsDateOk(ErrorMessage="Dates must be .....")]
public property DateTime MyTime {get; set ;}
The nice part about doing this is that you basically dont need to code anything on the front end and just need to display the @Html.ValidationMessageFor( x=> ....)
to make this work
Upvotes: 2