Jay Corbett
Jay Corbett

Reputation: 28411

Validating HTML text box with javascript and regex

The below code works to only allow alphanumerics and spaces. However, I would like to also allow an accented character (Ã). How should the regex be modified?

Thanks

<html>
<head>
<script type='text/javascript' src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/JavaScript">
 $(function() {
  $("#sub").bind("click",
   function() {
    $('#addText').val($('#addText').val().replace(new RegExp("[^a-zA-Z0-9 ]","g"), ''));
  });
 });
</script>
</head><body>
 <div>Enter Text:</div>
 <input id="addText" type=text/>
 <input id="sub"  type="button" value="Submit" />
</body></html>

Upvotes: 2

Views: 2593

Answers (2)

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195992

If you just want to add this one character .. just add it in the regex

[^a-zA-Z0-9Ã ]

Keep in mind though that there might be complications as mentioned below so do follow the suggestion by Laurence Gonsalves

Upvotes: 0

Laurence Gonsalves
Laurence Gonsalves

Reputation: 143154

If you only care about Latin-1 (Western European) letters, this should work:

[A-Za-z\xc0-\xd6\xd8-\xf6\xf8-\xff]

For other scripts (eg: Greek, Cyrillic, Thai letters, CJK characters, etc.) things get much more complicated, and it becomes safer to just forbid things like control characters, rather than trying to keep track of which characters are "letters".

Upvotes: 2

Related Questions