html - Javascript input validation -


how ensure there no special characters in name except apostrophe...eg:- can allow o'connor not john "doe" ? please help.

here's working example of how you'd use regular expression check valid name given conditions laid out:

<!doctype html> <html> <head>     <title>check name</title>     <script>     var goodname = /^[a-za-z'\s]+$/;      function checkname(name){         if (goodname.test(name)) {             alert("name 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, , spaces. (it's similar 1 proposed afiefh, addition of \s allow spaces, , + instead of * prevent blank names passing test.)

as david dorward suggests above, if using test names, might consider relaxing rule accommodate international names changing line 6 this:

var goodname = /^([ \u00c0-\u01ffa-za-z'\-])+$/; 

this allows unicode characters, apostrophes, , hyphens.


Comments