如果在该字段中键入了5位以上的数字,并且我将其另存为9位数字的字符串(如{{1,则如何)在美国邮政编码的5位数字之后(使用AngularJS)自动添加-
}})进行验证?
index.html
12345-6789
index.controller.js
<div class="field">
Country: {{location.zipcode}}
</div>
用户不是自己添加...
$scope.validateZipCode = function(location.zipcode) {
return (zipcode.length === 5 || (zipcode.length === 10 && zipcode[5] === '-'));
}
...
,我觉得拥有一个自动填充的-
是不错的UX。
请不要建议使用任何库或邮政编码验证API。这是一个遗留项目,需要最少的添加。
答案 0 :(得分:2)
不会有开箱即用的方法,因此您必须创建一个函数来计算字符并在需要时插入连字符。
这是您如何进行操作的基本示例。
const input = document.getElementById('zip');
document.addEventListener('keyup', e => {
const val = e.target.value;
if (val.length < 6) { input.value = e.target.value; }
if (val.length > 5) {
// There are better ways to do this part, but here's the basic idea
input.value = input.value.replace('-', '');
input.value = input.value.substring(0, 5) + '-' + input.value.substring(5, input.value.length);
}
});
<input id="zip" />
要注意的一件事是,您可以使用pattern attribute
的即用型方法来验证您的输入要求