简体   繁体   English

Java脚本验证符号%不能在文本字段中使用

[英]Java script validation symbol % must not allow in text field

I am working in javascript. 我正在使用JavaScript。 I want to add validation on my text field that only characters are allowed. 我想在我的文本字段中添加仅允许字符的验证。

along with characters, I allowed left arrow key which has keycode 37. But this is creating problem because keycode of % is also 37. And I dont want to allow % symbol. 与字符一起,我允许使用键码为37的向左箭头键。但这会造成问题,因为%的键码也为37。而且我不想允许%符号。

Please suggest me how can I differenciate % and left arrow key , because both key code are 37 ? 请建议我如何区分%和左箭头键,因为两个键代码均为37?

If you press the 'percent' key the char code is 37, for the 'left arrow'-key it's not 37; 如果按“百分比”键,则字符代码为37,对于“向左箭头”键,字符代码为37; eg: 例如:

$('#test').keypress(function(oEvent) {
    if (oEvent.charCode == 37) {
        return false;
    }
});

Also see this jsfiddle . 另请参阅此jsfiddle

=== UPDATE === ===更新===

For additional internet explorer support: 对于其他Internet Explorer支持:

$('#test').keypress(function(oEvent) {
    var iCode = typeof oEvent.charCode == 'number' ? oEvent.charCode : oEvent.keyCode;
    if (iCode == 37) {
        return false;
    }
});

Also see this jsfiddle . 另请参阅此jsfiddle

Don't limit the keypresses for validation. 不要限制按键的有效性。 People can just copy/paste to overcome that. 人们可以复制/粘贴来克服这一点。

You need to use Regex so validate your input. 您需要使用正则表达式,以便验证您的输入。

Learn more about it from https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp https://developer.mozilla.org/zh-CN/JavaScript/Reference/Global_Objects/RegExp了解更多

You should validate your user input after the user submits the form. 用户提交表单后,您应验证用户输入。 You can write a function that the form's "onsubmit" attribute runs before the data is submitted to the server, or you can set the form action to "action='javascript:someFunction()'" either way will work. 您可以编写一个函数,在将数据提交到服务器之前运行表单的“ onsubmit”属性,或者可以将表单操作设置为“ action ='javascript:someFunction()'”,这两种方法都可以。 Disallowing keystrokes makes the user interface more complicated and cumbersome for the end user and poses security risks for xss or injection attacks. 禁止击键操作会使最终用户的用户界面更加复杂繁琐,并给xss或注入攻击带来安全风险。 I would advise checking user input with javascript and returning an error message if it is invalid, then on the server side validating the data once more, and sanitizing the data. 我建议您使用javascript检查用户输入,如果无效,则返回错误消息,然后在服务器端再次验证数据并清理数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM