Kanishka Panamaldeniya
Kanishka Panamaldeniya

Reputation: 17576

how to validate text for only , English characters and , Non English characters jquery validater

I want to validate a text box to ensure only characters and Unicode characters can be added to it. For example, the following would be valid:

Gräfelfing
Gießen
München

But these should be invalid:

Gräfelfing123
Gießen!@#$
München123#@#

I know how to validate for characters using validator method:

jQuery.validator.addMethod("lettersonly", function(value, element) {
      return this.optional(element) || /^[a-zA-Z]+$/i.test(jQuery.trim(value));
    }, "Letters only please"); 

But how can I add Unicode character validation to this? Please help, thanks in advance.


* UPDATE *

I tried a solution with the help of this question - Regular expression to match non-English characters.

But it is not working:

jQuery.validator.addMethod("lettersonly", function(value, element) {
      return this.optional(element) || /^[a-zA-Z\u0000-\u0080]+$/i.test(jQuery.trim(value));
    }, "Letters only please"); 

Upvotes: 1

Views: 4759

Answers (1)

Oleg V. Volkov
Oleg V. Volkov

Reputation: 22421

Javascript lacks built-in character classe for "all latin-based letters with diactrics", so you must decide yourself what you really want to accept.

For example:

  • do you want to accept Cyrillic (Russian, Bulgarian, Belorussian, etc)?
  • Do you want to support kana (Japanese) or hangul (Korean)?

Those all are "non-Englih (or, more correctly: non-Latin) letters" after all.

After you've decided:

  • consult code charts and just list all the ranges you want in your regexp
  • You can use this tool to create a regex filtered by Unicode block.

Example

To add diactrics to list of allowed chars in the check in your code, you can use /^[a-zA-Z\u0080-\u024F]+$/i
That will cover

  • Latin-1 Supplement
  • Latin Extended-A
  • Latin Extended-B ranges.

This should cover most of used diactrics and works will all examples you've provided.
Mix and match as you want.

Upvotes: 2

Related Questions