Validation to make sure time difference is inside 2 hours
I have start time and end time in my asp.net w开发者_开发问答eb application. Now i want to validate that if start time is selected say 10:00 AM then end time should be selected with the gap of 2 hours or less. Hence if i select 01:00 PM as a end time, then this should not happen.
How can i validate the same?
If you use addition or subtraction on a DateTime class it returns a TimeSpan which can be compared in a conditional.
When creating a new TimeSpan class you can set the hours minuets and seconds in this form:
new TimeSpan(hours, minutes, seconds);
In your case you want to use:
new TimeSpan(2, 0, 0);
Try something like this:
//Assuming you created your variables and assigned them somewhere above
DateTime startTime, endTime;
if(endTime - startTime > new TimeSpan(2, 0, 0)) {
//validation error
}
- Use a CompareValidator with type=DateTime to make sure EndTime > BeginTime. This will also validate they're both valid Time values.
- Use a CustomValidator (C# and optionally JavaScript) to enforce the 2 hour rule.
- Optionally add 1 or 2 RequiredFieldValidators
As mentioned you can use a custom validation implementation. This would check that the current time selected 'start' was no more than 2 hours previous (or exactly dependent on your conditions).
Another thing to look at is 'range-validation' which should accommodate your requirements. Take a look here on MSDN for examples: http://msdn.microsoft.com/en-us/library/aa479013.aspx#aspnet-validateaspnetservercontrols_topic5
精彩评论