我正在尝试写一个函数,它将从输入元素中获取内容,并尝试格式化在MM/YY输入框中输入的数字。下面是我的一个解决方案,我想减少它的行数。有没有人能帮我写一个更好的函数来做到这一点?
如果你看到这个,它会自动插入斜杠。工作演示:https://codepen.io/ermauliks/pen/EXBryQ?editors=1010
function formatString(string) {
return string.replace(
/^([1-9]\/|[2-9])$/g, '0$1/' // To handle 3/ > 03/
).replace(
/^(0[1-9]{1}|1[0-2]{1})$/g, '$1/' // 11 > 11/
).replace(
/^([0-1]{1})([3-9]{1})$/g, '0$1/$2' // 13 > 01/3
).replace(
/^(\d)\/(\d\d)$/g, '0$1/$2' // To handle 1/11 > 01/11
).replace(
/^(0?[1-9]{1}|1[0-2]{1})([0-9]{2})$/g, '$1/$2' // 141 > 01/41
).replace(
/^([0]{1,})\/|[0]{1,}$/g, '0' // To handle 0/ > 0 and 00 > 0
).replace(
/[^\d\/]|^[\/]{0,}$/g, '' // To allow only numbers and /
).replace(
/\/\//g, '/' // Prevent entering more than 1 /
);
}
event.target.value = formatString(value);发布于 2020-05-10 05:15:29
以下是一个增强版本,其中用户不输入/(自动添加),并允许删除(其他解决方案在删除斜杠时阻止):
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
);
}发布于 2017-07-26 12:58:56
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 `/`
);
}发布于 2017-07-23 05:09:10
你不能在用户输入的同时格式化一些东西,不要使用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>https://stackoverflow.com/questions/45259196
复制相似问题