[英]text field that only allow and number and dash and also accepts ctrl commands
[英]Input text field that only accepts numbers dash numbers
我试图使用jQuery来控制输入字段,以前我只有数字,可以使用$(this).autoNumeric()
,现在我遇到了需要更改“数字破折号”形式的输入字段的问题。
我尝试了该站点以及其他站点的一些链接,但均未成功,我只是UI的初学者,请帮助我。
您将需要使用正则表达式。 我不会仅仅依靠HTML5输入掩码。
/^\d+(-\d+)*$/
如果没有更严格的约束,就足够了。
$("#myfield").change(function(){
var isValid = $(this).val().match(/^\d+(-\d+)*$/);
if(!isValid){
alert('only numbers and hyphesn please');
return false;
}
});
简单的html:
<input id="myfield">
演示: http : //jsbin.com/jeziqifebu/1/edit
更新:
用户需要数字字符串,即3.4.5不仅仅是十进制数字。
$("#myfield").change(function(){
var pattern = /^\d+(\.\d{1,2})?(\.\d{1,2})?(-\d+(\.\d{1,2})?(\.\d{1,2})?)?$/;
var isValid = $(this).val().match(pattern);
if(!isValid){
alert('only numbers or valid range separated by hyphens please');
return false;
}
});
这将需要
2
2-3
2.3
2.3-4
2.3.4-5
2.3.4-5.6
2.3.4-5.6.7
此解决方案不允许您输入数字和单破折号: JS FIDDLE
<input onkeypress="return isNumberKey(event);">
var dashCount = 0;
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode;
if (charCode == 45) {
dashCount++;
}
if ((charCode > 47 && charCode <58) || (charCode == 45 && dashCount < 2))
{
return true;
}
return false;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.