How to Check Special Characters using JavaScript


jQuery helps to validate a form before submitting it. Many times you need to validate the text field for special characters and HTML tags in jQuery validation. Using JavaScript test() function, you can check the input string is valid or not.

The following JavaScript code checks whether the string is content only letters and numbers.

if(/^[a-zA-Z0-9]*$/.test(str) == false){
    //error message
}

You can also accept other characters as per your requirement. The following JavaScript code accepts letters (a-z and A-Z), numbers (0-9), spaces, hyphen(-), comma(,), and underscore(_) characters.

if(/^[a-zA-Z0-9- ,_]*$/.test(str) == false){
    //error message
}

Leave a reply

Connect With CodexWorld