Abby said:
I ask the user to enter a time in the formatio 12:30 PM. onChange I
send the string to this function. I'm using alert boxes to test
it...and am always getting the "Does not work" alert box. What am I
doing wrong?
function checkTime(pattern){
if(pattern.value.match(/[0-9] + :[0-9] + [0-9] + [aApP] + [mM]/)) {
This regular expression matches:
- a single digit /[0-9]/
- one or more spaces / +/
- a space / /
- a colon /:/
- a single digit /[0-9]/
- one or more spaces / +/
- a space / /
- the letters a, p, A, or P /[aApP]/
- one or more spaces / +/
- a space / /
- the letters m or M /[mM]/
Is this really what you want?
I'm guessing you think the "+"s are concatenation or something, used to
"assemble" the regular expression. They aren't required, and in fact,
the "+" has a special meaning in regular expression syntax, so it
doesn't even match a "+" character.
You probably want something like:
if (/^\s*(1[012]|[1-9]):[0-5][0-9] ?[ap]m/i.test(pattern.value)) {
This matches (case-insensitively):
- from the beginning of the line /^/
- zero or more whitespace /\s*/ - accounts for any spaces the user
might enter
- the digit "1" /1/ followed by the digits 0, 1 or 2 [012]; OR
- the digits 1 to 9 /[1-9]/
- a colon /:/
- the digits 0 to 5 /[0-5]/
- the digits 0 to 9 /[0-9]/
- an optional space / ?/ - in case your users don't enter one
- the letters a or p /[ap]/
- the letter m /m/
It should match:
1:00am
12:30 PM
4:37 Am
I haven't tested it thoroughly, but it seems to do what you want.