I created a simple custom validation to make sure time entered is in a 12 hour format and the text input has a '99:99' mask set, so I will get:
12:00
The validation works great on the server:
private ValidationResult ValidateTwelveHourFormat(string time, ValidationContext validationContext) { if (String.IsNullOrWhiteSpace(time.Substring(0, 1)) || Convert.ToInt32(time.Substring(0, 1)) > 1 || Convert.ToInt32(time.Substring(1, 1)) > 2 || Convert.ToInt32(time.Substring(3, 1)) > 5) { return new ValidationResult(FormatErrorMessage(validationContext.DisplayName)); } return ValidationResult.Success; }
However, the same validation on the client does not behave the way I would expect:
$.validator.unobtrusive.adapters.addSingleVal('timeformat', 'format'); $.validator.addMethod('timeformat', function (value, element, timeformat) { if (value) { if (timeformat == "TwelveHour") { if (value.toString().substring(0, 1) == "" || value.toString().substring(0, 1) > 1 || value.toString().substring(1, 1) > 2 || value.toString().substring(3, 1) > 5) { return false; } } } return true; });
The client will correctly validate the first digit only. So if I entered a 3, it would trigger fine, but not for any other positions in the string. I threw some alerts in there and it seems to trigger the method when I enter a character into the text. This behavior confuses me because I didn't think this would fire before the form was first submitted, only after. Otherwise, the user would see error messages as they enter the form the first time and I don't believe that jives with the way validation typically works.
1.) Why isn't the client-side validating other character positions correctly?
2.) Why is the client validating when the form has yet to be submitted?
Update
1.) I used JavaScript's substr() as it acts like C#'s String.Substring().
For question 2 - I'm using Data Annoations with the mvc framework. Let's say I have a field set to be required. When I first enter that form, that field does not trigger validation on blur. I can enter crap, remove crap, but not trigger validation. That's why I'm confused. It seems to differ from the default behavior. I would think validation would be triggered after a submission attempt is attempted like the example I mentioned.