简体   繁体   中英

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. 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 .

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 .

It returns true for (afasdf) , but it actually matches afasdf . You should use ^n and n$ anchors.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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