1

I want to check whether a string has any special characters or not. I am using this script:

var name = $("#name").val(); if(name.match(/[_\W]0-9/)) { alert('Not A Name'); } 

It doesn't alert even when name="sas23"

1
  • 1
    for your purpose what are NOT special characters? (what characters are allowed?) Commented Jan 15, 2013 at 13:59

3 Answers 3

5

instead /[_\W]0-9/ your regex literal should be /[_\W0-9]/

Sign up to request clarification or add additional context in comments.

Comments

2

Your function should be like this:

var name=$("#name").val(); if(!isLetters(name)) { alert('Not A Name'); } function isLetters(str) { return /^[a-zA-Z]+$/.test(str); } 

Comments

0

You should always take a whitelist approach when creating regular expressions. That means specify which characters are allowed, and ban everything else by default. If all you want is letters, then only allow letters:

var name=$("#name").val(); if(!name.match(/^[a-z]+$/i)) { alert('Not A Name'); } 

Try it out.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.