简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM