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.
2 Answers
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.
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.