简体   繁体   中英

RegEx for Flexible Time Validation in JavaScript

I've begun with a regular expression for time validation, it should detect strings like:

5s
3h5m
5h3m02s
05:03:02
05:03
4

My current regex is valid for all of these but one: 05:03 . It detects 05 as hours and 03 as seconds , but it should be 05 as minutes... and I don't know how to edit my code to do this.

 var reTime =
 /^(?:PT)?(?:(\d{1,2})[:.hH])?(?:(\d{1,4})[:.mM])?(?:(\d{1,6})[sS]?)?$/;

Test this one :

var hasTimeFormat = function (input) {
        var timeFormat = /([0-9]{2})\:([0-9]{2})\:([0-9]{2})\,([0-9]{3})$/;
        if (typeof String.prototype.trim !== 'function') {
            String.prototype.trim = function () {
                return input.replace(/^\s+|\s+$/g, '');
            }
        }
        return timeFormat.test(input.trim());
    }

This works well (for example for "05:03:02,677") and if you wanna add something more, you can add easily.

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