2

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
parithi info
  • 243
  • 2
  • 4
  • 10

2 Answers2

2

Your 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
Mamun
  • 66,969
  • 9
  • 47
  • 59
  • for this case validateStr("sdsdsdsd45678") i need false to be return . – parithi info Dec 26 '18 at 14:03
  • 1
    @parithiinfo, simply remove `\d` from the regex......updated the answer....please check. – Mamun Dec 26 '18 at 14:11
  • @mamum its not allowed plain string , Ex: console.log (validateStr("sdsdsdsdsdsd"));// I should return true , but in ur case it returns false – parithi info Dec 27 '18 at 13:02
  • @parithiinfo, you can use `/[a-zA-Z]+([(@!#\$%\^\&*\)\(+=._-]{1,})?/` with quantifier `?`......but in that case `validateStr("sdsdsdsd45678")` will also be true...... – Mamun Dec 27 '18 at 13:19
  • If i use this , console.log(validateStr("sdsdsdsd45678")); this one is also come as true . – parithi info Dec 27 '18 at 14:10
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/185836/discussion-between-parithi-info-and-mamun). – parithi info Dec 27 '18 at 14:19
0

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;     
}
Majedur
  • 3,074
  • 1
  • 30
  • 43