简体   繁体   English

Javascript正则表达式只接受特定字符

[英]Javascript regular expression only accept specific characters

I need to validate a field when a form is submitted, but only specific characters are allowed. 我需要在提交表单时验证字段,但只允许使用特定字符。 Those characters are: 这些人物是:

a-z A-Z 0-9 % . " ' & - @ # $ * / + = [ ] !

I thought the following regex would work: 我认为以下正则表达式可行:

var regex = new RegExp(/[a-zA-Z0-9%\. "'&@#\$\*\/\+=\[\]\!-]+/); 

I tested it out https://regexr.com/4kigt , and it seems to match the pattern. 我测试了它https://regexr.com/4kigt ,它似乎匹配模式。 However, when I attempt to validate on form submit, it doesn't fail when characters like ( , ) , or ? 但是,当我尝试在表单提交时进行验证时,在()?类的字符时它不会失败? are entered. 进入。 For example, when I enter (afasdf) into the form field, the match is true . 例如,当我在表单字段中输入(afasdf) ,匹配为true

Any idea how to to fix this? 知道如何解决这个问题吗?

<input type="text" class="field">
<p>
    <button>Validate</button>
</p>
var field = document.querySelector('.field');
var button = document.querySelector('button');
var regex = new RegExp(/[a-zA-Z0-9%\. "'&@#\$\*\/\+=\[\]\!-]+/, 'g');

button.addEventListener('click', function() {
    console.log(regex.test(field.value));
}, false);

Jsbin link https://jsbin.com/forupos/edit?html,js,console,output . Jsbin链接https://jsbin.com/forupos/edit?html,js,console,output

It returns true for (afasdf) , but it actually matches afasdf . 它为(afasdf)返回true ,但它实际上与afasdf匹配。 You should use ^n and n$ anchors. 你应该使用^nn$ anchors。

var regex = new RegExp(/^[a-zA-Z0-9%\. "'&@#\$\*\/\+=\[\]\!-]+$/); 

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

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