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');
}
}
No comments:
Post a Comment