简体   繁体   中英

Using a regular expression to validate a time entry field in a PDF form

I have created the following JavaScript function in my PDF form:

var rgTime = /^[^0-9]{1,2}[^:][^0-9]{2}$/;
function testTimeEntry(t) {
if (rgTime.test(t)){
app.alert("Opps!  Time entry is invalid.  Only numbers and the colon(:) are allowed.");
event.value = "";
}
}

Then I use testTimeEntry(event.value); in the validation portion of my time field. However, it only works if I complete the field with 5 letters. I am basically trying to catch the accidental use of the semi-colon (or anything other than the colon) and alpha characters in this field.

I am not using the time format for the field on purpose, but I still need to make sure the inputted format is 12 hr (hh:mm). Thank you!

Your regular expression string rgTime = /^[^0-9]{1,2}[^:][^0-9]{2}$/ will only match with a string that is entirely invalid input. If the user inputs a valid 'hh' value then this regular expression will not match. As an example the string "11:1s" would not be matched by your regular expression.

Perhaps it would be easier to look for a valid input and alert them if it wasn't valid

var rgTime = /^[0-9]{1,2}[:][0-9]{2}$/;
function testTimeEntry(t) {
if (!rgTime.test(t)){
app.alert("Opps!  Time entry is invalid.  Only numbers and the colon(:) are allowed.");
event.value = "";
}
}

我会使用类似/[0-1][0-9]:[0-5][0-9]/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM