How to do date masking using javascript (without J

2019-01-23 09:54发布

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

5条回答
Bombasti
2楼-- · 2019-01-23 10:30

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

 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

查看更多
放我归山
3楼-- · 2019-01-23 10:34

Here is a more complete masking that allows backspaces and if a zero is forgotten to be typed before any month less than 10 it will add one, as well as a little help for the month. You'll have to excuse my javascript, but hey it works right?

<html>
<input placeholder="mm/dd/yyyy" onkeyup="this.value = fixDatePattern(this.value)">

<script>
  function fixDatePattern(currDate) {
    var currentDate = currDate;
    var currentLength = currentDate.length;
    var lastNumberEntered = currentDate[currentLength - 1];

    if (!isNumber(lastNumberEntered)) {
      return currentDate.substring(0, currentLength - 1);
    }

    if (currentLength > 10) {
      return currentDate.substring(0, 10);
    }

    if (currentLength == 1 && currentDate > 1) {
      var transformedDate = "0" + currentDate + '/';
      dateCountTracker = 2;
      currentLength = transformedDate.length;
      return transformedDate;
    } else if (currentLength == 4 && currentDate[3] > 3) {
      var transformedDate = currentDate.substring(0, 3) + "0" + currentDate[3] + '/';
      dateCountTracker = 5;
      currentLength = transformedDate.length;
      return transformedDate;
    } else if (currentLength == 2 && (dateCountTracker != 2 && dateCountTracker != 3)) {
      dateCountTracker = currentLength;
      return currentDate + '/';
    } else if (currentLength == 5 && (dateCountTracker != 5 && dateCountTracker != 6)) {
      dateCountTracker = currentLength;
      return currentDate + '/';
    }
    dateCountTracker = currentLength;
    return currentDate;
  }

  function isNumber(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
  }
</script>

查看更多
来,给爷笑一个
4楼-- · 2019-01-23 10:34

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.

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;
}
查看更多
家丑人穷心不美
5楼-- · 2019-01-23 10:41

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.

查看更多
Fickle 薄情
6楼-- · 2019-01-23 10:50

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!

查看更多
登录 后发表回答