[英]How to allow only characters on key press event for specific print range?
<input type="text" name="RangeText" id="rangeNum" onkeypress = "printValidation(event)" />
I am trying to allow only characters on key press event for specific pages range in the above print selection text box. 我试图在上述打印选择文本框中仅允许特定页面范围的按键事件上的字符。 I can do this easily with regex but want user to type only valid sccenarios!
我可以使用正则表达式轻松完成此操作,但希望用户仅键入有效脚本!
What I want to achive is as shown in below examples: 我要达到的目标如以下示例所示:
1 allow 1允许
1-2 allow 1-2允许
-2 not allow -2不允许
1, 2-3, 4, 5-7 allow 1,2-3,4,5-7允许
1 2, 3 not allow 1,2,3不允许
1-2-2 not allow 1-2-2不允许
This is how my current funtion looks like, the tricky part seems is not allowing negative number to begin with but allow the hyphen in the range! 这就是我当前的功能,棘手的部分似乎是不允许以负数开头,但允许连字符在范围内!
function printValidation(evt) {
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (!evt.shiftKey && !evt.altKey && !evt.ctrlKey && charCode >= 48 && charCode <= 57 || charCode == 188 || charCode == 109) {
alert("character accepted");
return true;
}else {
alert("illegal character detected");
return false;
}
}
Is there a possibility to achieve this without going in regex way? 是否有可能不用正则表达式来实现这一目标?
I suggest you allow the user to type only valid characters as you are doing (including hyphen, comma and space) and run a regex at the end (when you submit or lose focus of the field). 建议您在执行操作时仅允许用户键入有效字符(包括连字符,逗号和空格),并在末尾运行正则表达式(当您提交或失去该字段的焦点时)。 Or you could fill your function with a lot of
if
to test all the possibilities, ex. 或者你可以用很大的填补你的函数
if
测试一切准备,恩。 allow hyphen only after another character that's not hyphen, comma or space, etc. You can read the content of the field with evt.currentTarget.value
. 只能在另一个非连字符,逗号或空格等字符之后使用连字符。您可以使用
evt.currentTarget.value
读取字段的内容。 Hope that helps :) 希望有帮助:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.