parithi info
parithi info

Reputation: 263

How to check the string has number and special characters in JavaScript?

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

Upvotes: 2

Views: 11338

Answers (2)

Majedur
Majedur

Reputation: 3242

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;     
}

Upvotes: 0

Mamun
Mamun

Reputation: 68933

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

Upvotes: 2

Related Questions