Wednesday 12 June 2019

javascript - Multiple Regex validation for single value - alphanumeric with allowed special characters issue



Below is my regex for validating input name -starts with alphanumeric,allowed special characters.
It accepts "sample#@#@invalid" where am validating only allowed ()[].-_& characters.
where am doing wrong any help?



if(!/[A-Za-z0-9\s\)\(\]\[\._&-]+$/.test(inputText)){
alert('Field name should be alphanumeric and allowed special characters _ . - [ ] ( ) &');
}
if(!/^[A-Za-z0-9]/.test(inputText)){
alert('Field name must start with an alphanumeric');
}

Answer



Instead of negating the test, use a regular expression that inverts the character class:



if(/[^A-Za-z0-9\s)(\][._&-]/.test(inputText)){


Since this isn't anchored, it will match any character outside the allowed set anywhere in the input text.



function validate() {
var inputText = document.getElementById("inputText").value;
if (/[^A-Za-z0-9\s)(\][._&-]/.test(inputText)) {
alert('Field name should be alphanumeric and alllowed special characters _ . - [ ] ( ) &');
}
if (/^[^A-Za-z0-9]/.test(inputText)) {
alert('Field name must start with an alphanumeric');
}
}


DEMO


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...