Javascript 如何使用javascript(没有JQuery)进行日期屏蔽?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31108620/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:14:22  来源:igfitidea点击:

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

javascripthtmllocalemasking

提问by binbin

<![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.

如果语言环境等于'zh_CN',掩蔽将是'9999年99月99日'. 否则,它将是'99/99/9999'
当我删除 if else 命令时,它起作用了。但是如果我把 if else 命令放在里面,它就不起作用。

How do I solve it?

我该如何解决?

回答by Pratik Shah

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!

希望这就是你要找的!

回答by Chris Patty

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 followingit 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.

我还在这里为这个片段创建了一个 github 要点。

回答by Shubham Najardhane

Try out this code, this will format your date in mm/dd/yyyy format as you type it in the input box. Create an onchange event on the input box and call the date_formator function with the input date.

试试这个代码,当您在输入框中键入日期时,这会将您的日期格式化为 mm/dd/yyyy 格式。在输入框上创建一个 onchange 事件并使用输入日期调用 date_formator 函数。

function date_formator(date) {

    date = date.replace('//', '/');
    var result = date.split("/");

    var length = result.length;

    // Append "/" after the last two charas, if more than 2 charas then remove it
    if (length <= 2 && result[length - 1] != "") {
        var last_two_digits = result[length -1];
        if (last_two_digits.length >= 2) {
            date = date.slice(0, -last_two_digits.length);
            date = date + last_two_digits.slice(0,2) + "/";
        }
    }

    if (typeof result[2] != "undefined") {
        var year = result[2];
        if (year.length > 4) {
            date = date.slice(0, -year.length);
            year = year.slice(0, 4);
            date = date + year;
        }
    }
    return date;
}

回答by AbeCodes

This works quite well (tried it in console on the jquery mask page)

这很好用(在 jquery 掩码页面的控制台中尝试过)

 if (locale !=='' && locale==='zh_CN') {
          $('#text12').mask('9999年99月99日');
          }
          else {
          $('#text12').mask('99/99/9999');
          }

but if you want the mask format to show up in the input field you need to pass it as placeholder attribute

但如果您希望掩码格式显示在输入字段中,您需要将其作为占位符属性传递

$('#text12').attr('placeholder', '9999年99月99日')

hope this helps

希望这可以帮助