I have been looking for a decent jQuery validation methodology. I found this jsFiddle That does something similar
But I need mine to validate with AM\PM and also not be a required field for form submission. And If I could get this to work onBlur only then that would be great.
An example acceptable time would be
12:00 AM
While there is an infinite example of unacceptable strings, this is just one of them
24:00
Now that I think about it, I would want this thing not to submit if the format is not valid, but If there is no entered time, I don’t want the validator to fire.
Tried this with the jquery validator, but it is not working.
$().ready(function() {
$.validator.addMethod("time", function(value, element) {
return this.optional(element) || /^(([0-1]?[0-2])|([2][0-3])):([0-5]?[0-9])(a|p)m?$/i.test(value);
}, "Please enter a valid time.");
$("#login").validate({
rules: {
time: "required time",
},
});
});
I’d point you to the indispensible jquery.validator: http://docs.jquery.com/Plugins/Validation. Yeah, you’ll need to take a little time to figure it out but it is time well spent. When it comes to something as universally used as validation, someone has already done the heavy lifting, no need to reinvent the wheel, if you’ll excuse my overuse of metaphors.
Edit: I have had a change of opinion regarding validation. This may be somewhat tangential to the original question, but in general, I like the idea of masking/limiting fields to prevent 80-90% of user error, and the remainder can be validated via an ajax call to server-side FluentValidation. This strategy removes the need for jquery.validator and (most) other client-side validation. A workable and preferable approach in many situations. (Disclaimer: I am not affiliated with FluentValidation in any way other than as a user)