简体   繁体   中英

html5 time validation issue using pattern

I am using the HTML5 in build validation but for Time, i am sing the following code The code is pretty simple as it is just checking the format of the time, i am not sure what i am doing wrong here

<input name="taskStartTime" type="text" value="05:15 PM" placeholder="Enter a valid start time." size="10" pattern="/^\d{1,2}:\d{2}([ap]m)?$/" title="Enter Valid Time">

But it is not validating and it says invalid time, i think my regex is right, but not sure what is going on here...

Remove the forward slashes: they are part of JavaScript regex literal syntax, not part of general regex syntax. You don't really need the ^ and $ either because for an input element pattern they are implied.

The value you are setting in your example, 05:15 PM won't match your regex either, because it has a space in it and because the "PM" is in capitals. To allow for that:

pattern="\d{1,2}:\d{2}( ?[apAP][mM])?"

Note that for html5 input pattern attributes you can't set the i case insensitive flag that JavaScript (and some other regex implementations) allow. According to the specification it does use the JS syntax for the pattern itself, but "it is compiled "with the global, ignoreCase, and multiline flags disabled".

尝试这个

 <input name="taskStartTime" type="text" value="05:15 PM" placeholder="Enter a valid start time." size="10" pattern="^\\d{1,2}:\\d{2}\\s([AP]M)?$" title="Enter Valid Time"> 

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