I have the below function to find the string contains numbers and special characters, but it was not working
let validateStr = (stringToValidate) => {
var pattern = /^[a-zA-Z]*$/;
if (stringToValidate&& stringToValidate.length > 2 && pattern.test(stringToValidate))
{
return false;
} else {
return true;
}
};
validateStr("123$%^$") // I need the above function should return false.
validateStr("sdsdsdsd$%^$") // true
validateStr("sdsdsdsd") // true
validateStr("sdsdsdsd45678") // false
validateStr("$#*()%^$")//false
validateStr("123434333")//false
I have the below function to find the string contains numbers and special characters, but it was not working
let validateStr = (stringToValidate) => {
var pattern = /^[a-zA-Z]*$/;
if (stringToValidate&& stringToValidate.length > 2 && pattern.test(stringToValidate))
{
return false;
} else {
return true;
}
};
validateStr("123$%^$") // I need the above function should return false.
validateStr("sdsdsdsd$%^$") // true
validateStr("sdsdsdsd") // true
validateStr("sdsdsdsd45678") // false
validateStr("$#*()%^$")//false
validateStr("123434333")//false
Share
Improve this question
edited Dec 27, 2018 at 13:04
parithi info
asked Dec 26, 2018 at 11:07
parithi infoparithi info
2632 gold badges4 silver badges10 bronze badges
3
- Possible duplicate of Special character validation – Najam Us Saqib Commented Dec 26, 2018 at 11:17
- @Najamussaqib this is not duplicate, check the 4th function call, it was not working in your case .validateStr("$#*()%^$") check it with ur pattern. – parithi info Commented Dec 26, 2018 at 11:25
- Your pattern is entirely optional so everything will match. – Álvaro González Commented Dec 26, 2018 at 11:49
2 Answers
Reset to default 2Your RegEx should be:
/[a-zA-Z]+[(@!#\$%\^\&*\)\(+=._-]{1,}/
Try the following way:
let validateStr = (stringToValidate) => {
var pattern = /[a-zA-Z]+[(@!#\$%\^\&*\)\(+=._-]{1,}/;
if ( stringToValidate && stringToValidate.length > 2 && pattern.test(stringToValidate)) {
return true;
} else {
return false;
}
};
console.log(validateStr("123$%^$")); //false
console.log(validateStr("sdsdsdsd$%^$")); //true
console.log(validateStr("sdsdsdsd45678"));//false
console.log(validateStr("$#*()%^$")); //false
console.log(validateStr("123434333")); //false
You can use this code to track number and special characters in your string value.
function checkNumberOrSpecialCharacters(stringValue){
if( /[^a-zA-Z\-\/]/.test( stringValue) ) {
alert('Input is not alphabetic');
return false;
}
alert('Input is alphabetic');
return true;
}