Is there a plugin that serves as a mask and validator for 24h hours?

Asked

Viewed 89 times

2

I searched but only found plugins for time with "select" and schedules in formed AM/ PM.

I would like one that the person could type and stay in this format:

23:59:59

3 answers

3


This is more or less simple to do, ie a mask to insert : when entering numbers.

It can be more complex to not allow too large numbers and delete letters.

A simple example would be:

document.getElementById('hora').addEventListener('keyup', function(e){
    var str = this.value.split(':').join('');
    if (str.length > 6) str = str.slice(0, 6);
    var formatado = str.match(/.{1,2}/g).join(':');
    this.value = formatado;
});

jsFiddle: http://jsfiddle.net/5hupmfr9/

These 4 lines of code explained:

  • remove : any that may be in the string
  • take the last character if it is too long
  • break into two-character chunks and paste again with : among them
  • put back in input

1

0

I used jQuery-Mask-Plugin: http://igorescobar.github.io/jQuery-Mask-Plugin/

And I did the 24-hour validations I needed. It doesn’t allow 24:59:59, 23:69:59 or 23:59:69, for example.

<script type="text/javascript" src="~/Scripts/jQueryMask/jquery.mask.js">

</script>

<script type="text/javascript">
    $(document).ready(function () {
        var options = {
            onKeyPress: function (a, b, c) {
                if (a.length == 2) {
                    if (parseInt(a[1]) > 3 && parseInt(a[0]) == 2) {
                        a = a[0];
                        $(c).val(a);
                    }
                }
            },
            translation: {
                A: { pattern: /[0-2]/ },
                C: { pattern: /[0-5]/ },
                B: { pattern: /[0-9]/ }
            }
        };

        $('.time').mask('AB:CB:CB', options);
    })
</script>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.