JavaScript - 正则表达式信用卡到期日自动格式

时间:2017-07-22 21:01:06

标签: javascript regex

我正在尝试编写一个从输入元素获取内容的函数,并尝试格式化在MM / YY中输入框中输入的数字。以下是我的解决方案,我希望减少它拥有的行数。任何人都可以帮我写一个更好的功能吗?

如果你看到这个,它会自动插入斜线。工作演示:https://codepen.io/ermauliks/pen/EXBryQ?editors=1010

from keras.utils.visualize_util import plot  
plot(vfnet, to_file='model.png') 

3 个答案:

答案 0 :(得分:3)

    function formatString(e) {
  var inputChar = String.fromCharCode(event.keyCode);
  var code = event.keyCode;
  var allowedKeys = [8];
  if (allowedKeys.indexOf(code) !== -1) {
    return;
  }

  event.target.value = event.target.value.replace(
    /^([1-9]\/|[2-9])$/g, '0$1/' // 3 > 03/
  ).replace(
    /^(0[1-9]|1[0-2])$/g, '$1/' // 11 > 11/
  ).replace(
    /^1([3-9])$/g, '01/$1' // 13 > 01/3 //UPDATED by NAVNEET
  // ).replace(
  //   /^(0?[1-9]|1[0-2])([0-9]{2})$/g, '$1/$2' // 141 > 01/41
  ).replace(
    /^0\/|0+$/g, '0' // 0/ > 0 and 00 > 0 //UPDATED by NAVNEET
  ).replace(
    /[^\d|^\/]*/g, '' // To allow only digits and `/` //UPDATED by NAVNEET
  ).replace(
    /\/\//g, '/' // Prevent entering more than 1 `/`
  );
}

答案 1 :(得分:0)

你无法在用户输入的同时格式化某些东西,不要使用onkeyup,想象一下用户的噩梦! (他想键入12/18,当他输入1时,输入内容立即变为01!)。

我认为更好的方法是在表单中使用两个输入字段,并在输入字段使用onblur事件丢失焦点时触发格式化函数:

<script type="text/javascript">
(function() {
    document.addEventListener('DOMContentLoaded', function() {
        var myform = document.getElementById('myform');
        function formatExpMonthYear() {
            var val = this.value.replace(/\D+/g, '');
            this.value = /^\d$/.test(val) ? '0' + val : val;
            // fire a validation function/display a validation icon
        }
        myform.elements.expMonth.addEventListener('blur', formatExpMonthYear);
        myform.elements.expYear.addEventListener('blur', formatExpMonthYear);
        myform.addEventListener('submit', function() {
            // fire validation functions/display validation icons
        });
    });
})(); 
</script>
...
<form id="myform">
    <input placeholder="MM" type="text" name="expMonth" pattern="\d\d?"/>
    /
    <input placeholder="YY" type="text" name="expYear" pattern="\d\d?"/>
    <input type="submit"/>
</form>

答案 2 :(得分:0)

这是增强版本,用户无需输入/(自动添加)即可删除(其他解决方案会在删除斜杠时阻止):

function cc_expires_format(string) {
    return string.replace(
        /[^0-9]/g, '' // To allow only numbers
    ).replace(
        /^([2-9])$/g, '0$1' // To handle 3 > 03
    ).replace(
        /^(1{1})([3-9]{1})$/g, '0$1/$2' // 13 > 01/3
    ).replace(
        /^0{1,}/g, '0' // To handle 00 > 0
    ).replace(
        /^([0-1]{1}[0-9]{1})([0-9]{1,2}).*/g, '$1/$2' // To handle 113 > 11/3
    );
}
相关问题