views:

334

answers:

1

I am using jquery-1.3.2.js with the jquery.validate.js plugin and I am using the following code to try and validate an optional time field.

$.validator.addMethod('time', function(value) {
    return /(^([0-9]|[0-1][0-9]|[2][0-3]):([0-5][0-9])(\s{0,1})(AM|PM|am|pm|aM|Am|pM|Pm{2,2})$)|(^([0-9]|[1][0-9]|[2][0-3])(\s{0,1})(AM|PM|am|pm|aM|Am|pM|Pm{2,2})$)/.test(value);
}, 'Please enter a valid time in the format of mm:hh am');

    $.validator.addClassRules({
    time: {
        required: true,
        time: true
    },
    timeOptional: {
        required: false,
        time: true
    }

});

When I add a class to my textbox that is of "timeOptional", and I do not enter anything in the textbox, when the form is submitted I get the message of "Please enter a valid time in the format of mm:hh am."

How can I change this so that the form will allow a null value to be submitted in this textbox?

A: 

You could add a {0,1} to the end of the regex of the whole grouping to signify 0 or 1 entries.

Stefan Kendall
I'm afraid I'm a bit of a tard when it comes to regex. I could not get this working. It would accept an empty textbox, but it ended up accepting anything else as well. I ended up making another function using the original regex but added if(value=="")return true; else return the regex
Deke