在IE中使用大写字符将输入限制为指定的正则表达式 [英] Limiting input to specified regexp with uppercase chars in IE

查看:149
本文介绍了在IE中使用大写字符将输入限制为指定的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用javascript/jquery限制用户可以输入的内容.

I'm trying to limit what our users will be able to type in inputs, using javascript/jquery.

问题是,我必须将其限制为仅大写字符和数字.

Problem is, I have to limit this to Uppercase chars only, and numbers.

这是我之前编写的代码:

Here's what I coded previously :

$(input).keypress(function(e){
                    if ($(input).attr("class")=="populationReference"){
                        var ValidPattern = /^[A-Z_0-9]*$/;
                        var char = String.fromCharCode(e.charCode);
                        if (!ValidPattern.test(char) && e.charCode!=0){
                            return false;
                            e.preventDefault();
                        }
                    }
                });

如果Firefox支持charCode,则IE不支持.然后,如何测试用户输入的是大写还是小写字符? 感谢您的帮助!

If Firefox supports charCode, IE doesn't. How then, could I test if the user is typing uppercase or lowercase characters ? Thanks for any help !

推荐答案

从jQuery手册中获取 keypress() :

From the jquery manual for keypress():

确定哪个字符是 输入后,我们可以检查事件 传递给处理程序的对象 功能.虽然浏览器使用的是不同的 属性来存储此信息, jQuery规范化了.which属性 因此我们可以可靠地使用它来检索 字符代码.

To determine which character was entered, we can examine the event object that is passed to the handler function. While browsers use differing attributes to store this information, jQuery normalizes the .which attribute so we can reliably use it to retrieve the character code.

换句话说,如果您使用的是jquery,则可以安全地使用e.which返回字符代码,因此在您的情况下:

In other words, if you are using jquery, you are safe to use e.which to return the character code, so in your case:

var char = String.fromCharCode(e.which);

是要进行的更改.

但就我个人而言,我会避免通过为用户转换小写输入来惩罚用户.也许添加以下修改:

But personally, I would avoid punishing users for lower-case input by converting it for them. Maybe add this modification:

$("input.populationReference").keypress(function(e){
                        var ValidPattern = /^[A-Z_a-z_0-9]*$/;
                        var char = String.fromCharCode(e.charCode);
                        if (!ValidPattern.test(char) && e.charCode!=0){
                            return false;
                            e.preventDefault();
                        } else {
                          var inputval = $(this).value(); 
                          $(this).value(inputval.toUpperCase());
                        }
                });

这篇关于在IE中使用大写字符将输入限制为指定的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆