使用js和正则表达式检查文本框中的无效字符 [英] check a textbox for invalid characters using js and regular expressions

查看:162
本文介绍了使用js和正则表达式检查文本框中的无效字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我需要将一些ASP代码重写为html和js,并且我已经遇到了一个障碍这部分:

 < asp:RegularExpressionValidator runat =serverid =RegExpValidatorcontroltovalidate =FileNameDisplay =动态ValidationExpression =[^#%& *:<>?/ {|}] +> 

现在,我所做的是创建一个输入文本框,当内容发生变化时它将运行js函数。

 < input type =textid =fileNameTextBoxclass =ms-inputsize =35 maxlength =123onchange =regexValidator(this);/> 

function regexValidator(control){
var val = $(control).val();
if(val == undefined || val ==''){

$(control).attr(class,invalid);
}
else {
//正则表达式的东西放在这里
}
}

现在,在我的生活中,我无法弄清楚如何构造正则表达式。 ValidationExpression字段我假设检查无效字符,虽然它似乎不是一个正确构造的正则表达式,我不知道如何将它写入适当的与js一起使用。有人可以帮我解决这个问题吗?

解决方案

如果您希望正则表达式检查字段中的无效字符,您可以使用这个。

^。*?(?= [\ ^#%& $ \ *:<> \?/ \\ \\ {\ | \}])。* $ 如果至少有一个无效字符,这会给您一个匹配。


I am having a hard time figuring out how RegExp work.

I need to rewrite some ASP code into html and js, and I've hit an obstacle in this part:

<asp:RegularExpressionValidator runat="server" id="RegExpValidator" controltovalidate="FileName" Display="Dynamic" ValidationExpression="[^#%&*:<>?/{|}]+">

Now, what I do is create an input textbox which will run a js function whenever its content is changing.

<input type="text" id="fileNameTextBox" class="ms-input" size="35" maxlength="123" onchange="regexValidator(this);"/>

function regexValidator(control) {
            var val = $(control).val();
            if(val == undefined || val == '') {

                $(control).attr("class", "invalid");
            } 
            else { 
            // Regex stuff goes in here
            }
        }

Now, for the life of me I can't figure out how to construct the regular expression. The ValidationExpression field i assume checks for invalid characters though it doesn't seem to be a properly constructed regex, and I can't figure out how to write it into a proper one to use with js. Could someone help me out with this?

解决方案

If you want the regex to check for invalid characters in the field, you can use this.

^.*?(?=[\^#%&$\*:<>\?/\{\|\}]).*$ This will give you a match if there is at least one invalid character.

这篇关于使用js和正则表达式检查文本框中的无效字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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