JS Mask for Hours Validation

Asked

Viewed 14,943 times

20

I’m using in a project the jQuery Masked Input. I made a mask like this:

<script>
    $(document).ready(function () {
        $("#QuantidadeHoras").mask("99:99");
    });
</script>

The <input> just let me fill in the field with numbers, but I can type an invalid time, for example, 88:88. The right thing would be to fill in the minutes between 00 and 59.

How can I make the mask not allow this kind of fill?

  • Check out if you can solve this: http://stackoverflow.com/questions/2259843/jquery-masked-edit-for-time

  • 1

    I tried to create a fiddle with the answer code of the link I posted above, but I couldn’t... By the way, nor the jQuery Masked Plugin seems to have this possibility (on the demo page itself it accepts 99:99). I think it will be difficult to get something like input time (too bad few browsers accept). I am also interested in this answer, because to change the date (I was using the date) I am suffering here, and I still have the hours to change (I didn’t even start :/). So I hope you find(mos) a good answer! :-)

  • 1

    Want a solution for modern or old browsers as well? this plugin does not allow this, but it can make a "custom" version if you do not have to use this plugin. I will see if I find an agnostic tb.

  • @Sergio No need for retroactive compatibility. I will guide users to always use the most updated possible versions of the respective browsers. I am very interested in the version custom.

  • @Ciganomorrisonmendez, your project employs a standard of 12 (am/pm) or 24 hours?

  • @Caiofelipepereira Hours is a free field, but if you want to make an answer to 24h, ok.

  • 2

    @Ciganomorrisonmendez para 12h is easy to restrict, using the plugin suggested in Guilherme Diego’s reply. For 24 hours, there is a parole that is hard to get out. I keep trying here and I warn you

  • 1

    @I have not yet had time to finish a "custom Mask" for this case. The idea I’m working on is this: http://jsfiddle.net/hqob3wxj/ do what you want?

  • The correct answer should be from @master-Oak

Show 4 more comments

6 answers

16


I had to put in a pastebin why don’t you let me pull the source, but the originals are:

<script type="text/javascript" src="https://raw.githubusercontent.com/RobinHerbots/jquery.inputmask/2.x/js/jquery.inputmask.js"></script>
<script type="text/javascript" src="https://raw.githubusercontent.com/RobinHerbots/jquery.inputmask/2.x/js/jquery.inputmask.extensions.js" ></script>
<script type="text/javascript" src="https://raw.githubusercontent.com/RobinHerbots/jquery.inputmask/2.x/js/jquery.inputmask.date.extensions.js"></script>

$(document).ready(function(){
    $("#time").inputmask("h:s",{ "placeholder": "hh/mm" });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="https://pastebin.com/raw/5ZtAJd0v"></script>
<script type="text/javascript" src="https://pastebin.com/raw/fb6hwXMD"></script>
<script type="text/javascript" src="https://pastebin.com/raw/fkjwWpFs"></script>

<div>
    <input type="text" id="time" value=""/> 
</div>

More information here: https://github.com/RobinHerbots/jquery.inputmask/blob/3.x/README_date.md

Using the 3.x I couldn’t make it work.

5

I advise you to use the http://igorescobar.github.io/jQuery-Mask-Plugin/

If you take a look he has an option of pattern that from what I understand you can configure a Regexp with the crease accepted to your mask.

The code would look like this for example:

var mask = "HH:MM",
    pattern = {
        'translation': {
            'H': {
                pattern: /[0-23]/
            },
            'M': {
                pattern: /[0-59]/
            }
        }
    };

$("#QuantidadeHoras").mask(mask, pattern);

jsFiddle: http://jsfiddle.net/2oxak786/

  • 1

    this pattern is not only to allow the user to type only numbers ?

  • 1

    Okay, and what’s the Pattern? That’s what I want in the answer.

  • var Mask = "00:11", Pattern = {'Translation': { 0 : {Pattern:/[0-24]/}, 1 : {Pattern:/[0-59]/} }}; $(". masktest"). Mask(Mask, Pattern);

  • @Ciganomorrisonmendez http://jsfiddle.net/nrfmf3n4/1/ One correction for pattern the correct is [0-23]

  • 2

    @Maiconcarraro It got weird. I typed "15" and switched to "11".

  • how do I get permission to enter the hours 14:00, 15:00, 16:00 and etc ?

  • The example in jsFiddle does not allow typing 06:00 ?

Show 2 more comments

4

It is also possible to solve this problem using pure javascript, with the following regex:

([01][0-9]|2[0-3]):[0-5][0-9]

Entrances:

válidas
20:59
00:59
01:01
10:30
00:00

inválidas
24:59
30:01
00:60
05:122

Example

  • It was cool, but I needed that logic on <input type="text">.

  • 2

    +1. I simply threw this into the attribute pattern of input and it worked :)

2

If you use Pablo’s library

   $("#hora").mask("AB:CD", {
        translation: {
          "A": { pattern: /[0-2]/, optional: false},
          "B": { pattern: /[0-3]/, optional: false},
          "C": { pattern: /[0-5]/, optional: false},
          "D": { pattern: /[0-9]/, optional: false}
        }
    });

Tested and working

Note: beware of commas and quotes in js

2

It is possible to use the , changing the mask with the event onKeyPress, depending on whether the hours have a value equal to or greater than 20.

var mask = function (val) {
    val = val.split(":");
    return (parseInt(val[0]) > 19)? "HZ:M0" : "H0:M0";
}

pattern = {
    onKeyPress: function(val, e, field, options) {
        field.mask(mask.apply({}, arguments), options);
    },
    translation: {
        'H': { pattern: /[0-2]/, optional: false },
        'Z': { pattern: /[0-3]/, optional: false },
        'M': { pattern: /[0-5]/, optional: false }
    },
    placeholder: 'hh:mm'
};

$(document).ready(function () {
  $("#QuantidadeHoras").mask(mask, pattern);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.0/jquery.mask.min.js"></script>

<input type="text" id="QuantidadeHoras" />

2

Leaving here for future reference.

This example uses the following library: https://github.com/igorescobar/jQuery-Mask-Plugin

In the examples above, we have problems with the codes that use this library in the form of problems when generating schedules started with '0', for example (06:30, 08:30), so let’s expand the code a little:

HTML:

<input type="text" id="hora" />

JS:

var SPMaskBehavior = function (val) {
  return val.replace(/\D/g, '')[0] === '2' ? 'AE:CD' : 'AB:CD';
},
spOptions = {
  onKeyPress: function(val, e, field, options) {
      field.mask(SPMaskBehavior.apply({}, arguments), options);
    },
    translation: {
       "A": { pattern: /[0-2]/, optional: false},
       "B": { pattern: /[0-9]/, optional: false},
       "C": { pattern: /[0-5]/, optional: false},
       "D": { pattern: /[0-9]/, optional: false},
       "E": { pattern: /[0-3]/, optional: false}
    }
};

$('#hora').mask(SPMaskBehavior, spOptions);

What the above code does is detect if the first digit of the time was '0' or '1' and in this case allows the second digit to be between '0' and '9'. If the first digit of the time is '2', only allow it to be continued by '0-3'. Minutes are no secret, they proceed in the same way.

JSFIDDLE: http://jsfiddle.net/9cvLzmfs/

  • This should be the accepted answer.

Browser other questions tagged

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