[英]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.