How to do date masking using javascript (without JQuery)?

53,100

Solution 1

Check out the below code..

<input
    type="text"
    name="date"
    placeholder="dd/mm/yyyy"
    onkeyup="
        var v = this.value;
        if (v.match(/^\d{2}$/) !== null) {
            this.value = v + '/';
        } else if (v.match(/^\d{2}\/\d{2}$/) !== null) {
            this.value = v + '/';
        }"
    maxlength="10"
>

<input
    type="text"
    name="date"
    placeholder="mm/dd/yyyy"
    onkeyup="
        var v = this.value;
        if (v.match(/^\d{2}$/) !== null) {
            this.value = v + '/';
        } else if (v.match(/^\d{2}\/\d{2}$/) !== null) {
            this.value = v + '/';
        }"
    maxlength="10"
>
<input
    type="text"
    name="date"
    placeholder="yyyy/mm/dd"
    onkeyup="
        var v = this.value;
        if (v.match(/^\d{4}$/) !== null) {
            this.value = v + '/';
        } else if (v.match(/^\d{4}\/\d{2}$/) !== null) {
            this.value = v + '/';
        }"
    maxlength="10"
>
<input
    type="text"
    name="date"
    placeholder="yyyy年mm月dd"
    onkeyup="
        var v = this.value;
        if (v.match(/^\d{4}$/) !== null) {
            this.value = v + '年';
        } else if (v.match(/^\d{4}年\d{2}$/) !== null) {
            this.value = v + '月';
        }"
    maxlength="10"
>

Hope this is what you are looking for!

Solution 2

I had some trouble getting the currently accepted answers to work properly while retaining the ability to backspace. This was my solution. It retains backspacing and also doesn't show the slash until the number following it is typed.

const maskDate = value => {
  let v = value.replace(/\D/g,'').slice(0, 10);
  if (v.length >= 5) {
    return `${v.slice(0,2)}/${v.slice(2,4)}/${v.slice(4)}`;
  }
  else if (v.length >= 3) {
    return `${v.slice(0,2)}/${v.slice(2)}`;
  }
  return v
}

I've also create a github gist for this snippet here.

Share:
53,100
binbin
Author by

binbin

Updated on October 22, 2021

Comments

  • binbin
    binbin over 2 years
    <![CDATA[
        var $ = jQuery;
        String locale = getUserLocale();
        $(document).ready(function() {
    
            if (!isEmptyNull(locale) && locale.equals("zh_CN")) {
                $("input[id*='text12']").mask('9999年99月99日');
            }
            else {
                $("input[id*='text12']").mask('99/99/9999');
            }
        });
    ]]>
    
    <p:calendar id="text12" styleClass="calendar" maxlength="10" pattern="#
    {pc_Test.dateDisplayFormat}"></p:calendar>
    

    If the locale is equal to 'zh_CN', the masking would be '9999年99月99日'. Otherwise, it would would be '99/99/9999'.
    When I remove the if else command, it works. But if I put the if else command inside, it doesn't work.

    How do I solve it?

  • binbin
    binbin about 9 years
    Thanks for ur answer! But what I want is to mask the date format according to the different locale. For example, if my locale equals to en_US, the mask will be display 99/99/9999 which is __/__/____ But if my locale equals to zh_CN, the mask will be display ____ 年__月__日 Any ideas for this? Thanks
  • Pratik Shah
    Pratik Shah about 9 years
    Hi @binbin! In your case I guess you have to detect the location of the user and than change the "/" with local language! In cases like RTF reading you just need to change the order of the if and else if conditions.
  • binbin
    binbin about 9 years
    Hi @Pratik Shah, Thanks for ur examples. Let me try the code to see whether it work for me.
  • binbin
    binbin about 9 years
    HI @Pratik Shah It doesn't work. Can you give me some suggestion or examples that do the masking in the javascript like what I did above? Thanks!
  • Pratik Shah
    Pratik Shah about 9 years
    Can you show me which part of code is not working for you? So that I can help you with it? and it would be better if you can give me jsFiddle or something showcasing your desired output.
  • binbin
    binbin about 9 years
    Hi @AbeCodes, Thanks for your answer. But it doesn't work for me :( For the placeholder, I'm using watermark and it's work well. Just that the mask can't show up.
  • binbin
    binbin about 9 years
    When my locale equals to zh_CN, the mask doesn't change to 9999年99月99日. Can you show me some examples of using mask instead of onkeyup?Thanks :)
  • AbeCodes
    AbeCodes about 9 years
    @binbin try a timeout, maybe the input isnt rendered at this point, the code works fine ;) or maybe there is a problem with watermark?
  • binbin
    binbin about 9 years
    I tried and i guess the problem is the if else command because when I remove the if else command, it works well. I think there is a problem with locale and i don't know why they can't get the locale properly :(
  • AbeCodes
    AbeCodes about 9 years
    go with var locale and check via if (locale !=='' && locale==='zh_CN'). and check with console.log(locale) if a value is set.
  • AbeCodes
    AbeCodes about 9 years
    you get a value for locale?
  • binbin
    binbin about 9 years
    No. There is nothing come out.
  • AbeCodes
    AbeCodes about 9 years
    you need to fix the function and then it should work ;)
  • binbin
    binbin about 9 years
    I found out that there is the problem with locale. There is "Uncaught ReferenceError: getUserLocale is not defined". Do you know how to call the locale in javascript?
  • AbeCodes
    AbeCodes about 9 years
    this error tells you that the function is not defined. i dont know your code or site. if the locale is passed via cookie you can read the cookie value. or if you pass it via body class attribute you can read this.
  • binbin
    binbin about 9 years
    Thanks. I will check it out :)
  • AbeCodes
    AbeCodes about 9 years
    Have fun ;) Tell me if it works and dont forget to upvote if it does ;)
  • Jorge Campos
    Jorge Campos about 6 years
    That's awesome. I added some few validations for Brazil's time and also the delete and backspace keys.
  • Selva Ganapathi
    Selva Ganapathi over 4 years
    its take 78 on day option its should be less than 12 right? how to add the conditions?
  • Pratik Shah
    Pratik Shah over 4 years
    Hi @SelvaGanapathi, suggested solution is only for the length of the input and not for the value validation.
  • asela daskon
    asela daskon over 3 years
    Not a good solution because a user could try string instead of an integer. Must restrict only for integer
  • Tom Pietrosanti
    Tom Pietrosanti over 3 years
    Nice and clean. Though this only works if the user always enters 2-digit months and days. Handling 1-digit day/month gets trickier (like 1/1/1970).