1

How do I ensure that there are no special characters in the name except an apostrophe...Eg:- I can allow O'Connor but not John "Doe" ? Please help.

1
  • 2
    People do have accented characters and hyphens in their names (for example). This is an area where you should be really liberal in what you accept. Commented Apr 29, 2011 at 15:19

2 Answers 2

2

Use a regular expression, if you want only English characters with an apostrophe use ^[A-Za-z\']*$ you can extend this to check for a LOT of things. Regular Expressions are a very powerful tool and I'd advise reading up on them(they exist in pretty much every programming language)

var validRegex = /^[A-Za-z\']*$/; 
if(myString.search(validRegex)==-1) 
     alert("Error");

Edit: added example.

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

2 Comments

Not to nitpick, but that is a hyphen not an apostrophe.
Oops, my bad. Edited in a fix.
1

Here's a working example of how you'd use a regular expression to check for a valid name given the conditions you laid out:

<!DOCTYPE html>
<html>
<head>
    <title>Check for a good name</title>
    <script>
    var goodName = /^[A-Za-z'\s]+$/;

    function checkName(name){
        if (goodName.test(name)) {
            alert("Name is great!");
        } else {
            alert("Name contains illegal characters");
        }
    }      
    </script>
</head>
<body>
    <form onsubmit="return false;">
        <input type="text" name="name" size="20">
        <input type="button" value="Check" 
                             onclick="checkName(this.form.name.value);">
    </form>
</body>
</html>

The /^[A-Za-z'\s]+$/ regular expression allows uppercase English, lowercase English, apostrophes, and spaces. (It's similar to the one proposed by Afiefh, with the addition of the \s to allow spaces, and the + instead of the * to prevent blank names from passing the test.)

As David Dorward suggests above, if you really are using this to test names, you might consider relaxing the rule to accommodate international names by changing line 6 to this:

var goodName = /^([ \u00c0-\u01ffa-zA-Z'\-])+$/;

This allows unicode characters, apostrophes, and hyphens.

2 Comments

I just tried your code but it's accepting everything...quotation marks and other special characters...
Really? It's working fine for me. Here's a working version: jsbin.com/ereyi3 and here it is with the international regex: jsbin.com/uvowe4

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.