Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to disallow all Special Chars but allow German Umlauts in jQuery?

I would like to allow all Alphanumeric Characters and disallow all Special Characters in a RegEx. But I would like to allow German Umlauts but becouse they are Special Chars too, I can't type them in. I use this Script:

    if(website_media_description.match(/[^a-zA-Z0-9]/g)) { 

    alert('Found Special Char');        

}

So when a äöüÄÖÜß is in the variable than I get the alert too. I also tryed this Script:

    if(website_media_description.match(/[^a-zA-Z0-9äöüÄÖÜß]/g)) { 

    alert('Found Special Char');        

}

But this also does not work. Can someone please tell me what I am doing wrong?

Thanks :)

like image 547
Thorsten Avatar asked Jun 17 '13 17:06

Thorsten


People also ask

How do you restrict special characters in regex?

var nospecial=/^[^* | \ " : < > [ ] { } ` \ ( ) '' ; @ & $]+$/; if(address. match(nospecial)){ alert('Special characters like * | \ " : < > [ ] { } ` \ ( ) \'\' ; @ & $ are not allowed'); return false; but it is not working.

How do you specify all special characters in regex?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).

What is Slash's regex?

The backslash in combination with a literal character can create a regex token with a special meaning. E.g. \d is a shorthand that matches a single digit from 0 to 9. Escaping a single metacharacter with a backslash works in all regular expression flavors.


2 Answers

my test String comes from an input field, i write "description test 1 öäüÖÄÜß"

Your problem is coming from the fact you haven't considered every character you want in your whitelist.

Let's consider what is actually matched by your test string

"description test 1 öäüÖÄÜß".match(/[^a-zA-Z0-9äöüÄÖÜß]/g);
// [" ", " ", " "]

As we can see, it matched 3 times, and each time was whitespace. So, the solution is to add a space to your whitelist (assuming you don't want to allow tab/return etc).

"description test 1 öäüÖÄÜß".match(/[^a-zA-Z0-9äöüÄÖÜß ]/g);
// null

Your test string now passes the RegExp without a match, which means it is valid in this case.

like image 190
Paul S. Avatar answered Oct 23 '22 02:10

Paul S.


For some reason I needed to use the unicode representation:

[^a-zA-Z0-9\u00E4\u00F6\u00FC\u00C4\u00D6\u00DC\u00df]`

Thanks to everyone :)

like image 24
Thorsten Avatar answered Oct 23 '22 02:10

Thorsten