When submitting a form, I need to validate a field and ensure that only specific characters are allowed. The permitted characters include:
a-z A-Z 0-9 % . " ' & - @ # $ * / + = [ ] !
I attempted to use the following regex for validation:
var regex = new RegExp(/[a-zA-Z0-9%\. "'&@#\$\*\/\+=\[\]\!-]+/);
After testing it on , it appeared to match the pattern correctly. However, during form submission validation, it did not reject input containing characters such as (
, )
, or ?
. For instance, entering (afasdf)
in the form field resulted in a true match.
Any suggestions on how to resolve this issue?
<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.