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

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 :)

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.

For some reason I needed to use the unicode representation:
[^a-zA-Z0-9\u00E4\u00F6\u00FC\u00C4\u00D6\u00DC\u00df]`
Thanks to everyone :)

Related

JavaScript Regex For Sentence Not Working

So I am trying to write a regex to validate a normal sentence with no weird characters other than the basic ones you would see in a sentence (e.g: .,':<>... etc) and that is no longer than 512 characters. I am struggling to figure out how to do this, even after trying to look up the appropriate documentation for it.
The test code with the regex I have right now is below, however this does not work unless I remove all special characters:
const sentence = "This is a test sentence with some special characters ./<>'...";
if (/^[\w]{1,512}$/i.test(sentence)) {
console.log("You provided a valid sentence.");
}
How do I make it so that this regex allows for basic sentence characters?
Also, are there any helpful tools that I can use to create regex's for JavaScript? Thanks in advance.
Edit: I now realize that I need to just add in all the characters that I want to allow, but now I am unsure how to do so without breaking syntax and including the ' and " characters.
const sentence = "This is a test sentence with some special characters ./<>'...";
if (/^[\w~!##$%^&*()_+{}[]:";\'<>?,./]{1,512}$/i.test(sentence)) {
console.log("You provided a valid sentence.");
}
After help from others in the comments of my original post, I managed to get what I wanted with the following code:
const sentence = "This is a test sentence with some special characters ./<>'...";
if (/^[\w~!##$%^&*()_+{}[]:";\'<>?,.\/]{1,512}$/i.test(sentence)) {
console.log("You provided a valid sentence.");
}
Thank you to those who helped me!

Distinguish '$' and '\$' in a string using javascript indexOf method

Suppose the following data is entered by user in a text area
test\$ing
I need to extract and modify the data. Problem is that I am not able to distinguish between '$' and '\$'
I have made the following attempts.
indexOf('\\') gives -1
indexOf('\$') gives 4
indexOf('$') gives 4
charAt(4) gives $
I understand that java script treat '\$' as a single character. But how to distinguish whether the character is '$' or '\$'
I have gone through this post and the accepted solution suggests to change the original text by escape backslashes. Is this the only possible way? Even if this is the case, how to escape the backslashes in the original text?
Please help
\ is an escape character, which means that in order to get a literal version of that character you have to write two of them in a row. Thus, your string should be written as 'test\\$ing' in JavaScript source. (However, users don't need to escape this character when they are typing in the context of a <textarea>.) To find a blackslash followed by $ inside your string you would write:
string.indexOf('\\$') //=> 4
Demo Snippet:
var string = 'test\\$ing'
console.log(string.indexOf('\\')) //=> 4
console.log(string.indexOf('\\$')) //=> 4
console.log(string.indexOf('$')) //=> 5
console.log(string.charAt(4)) //=> '\'
If you work with a string 'test\$ing' then you can't detect '\' because it is removed.
If user types \$ inside textarea.value, then indexOf should work.
Please provide more code.

Javascript Simple check for webform to make sure it contains both numbers and letters (instead of my code)

I have this code:
if(address.length<=0)
{
msg.setAttribute("style", "color:red");
msg.innerHTML='Please enter address';
return false;
}
I would like to change so it checks whether the webform contains BOTH numbers and letters. Can you help me?
Thank you so much,
Jones
p.s.: So I want to make sure they also enter street name AND house number as well (example: 24 Sunshine street would be good, but if they forget house number, they would get the message).
That doesn't look like PHP at all. More like JavaScript...
Here's one way to do it in JavaScript:
var re = /^\d+\s+\D+$/;
if (re.test(address)) {
//We get here if the address is correctly formated
}
else {
//We get here if the string is badly formated
}
The regex works like this:
\d+ matches to one or more numbers
\s+ matches to one or more spaces
\D+ matches to one or more letters
If you want to accept both "24 Sunshine" and "Sunshine 24" you could instead use this:
/^(\d+\s+\D+)|(\D+\s+\d+)$/
And if we want to be extra safe and protect from the case that the user might enter an extra trailing or leading space we could either trail the string or use this ReGex:
/^\s*(\d+\s+\D+)|(\D+\s+\d+)\s*$/
Apart from regular expression which is a very nice and clear solution you can use these php functions:
first the ctype_alnum () in order to check if your string contains letters and digits and then
this on ctype_alpha() in case the above is true to check if user forgot to enter number.
In case you are interested there is also this one ctype_digit() for checking if user missed the address but gave the number.
Or if you want just a regex this it will do the job:
^[a-zA-Z]([a-zA-Z-]+\s)+\d{1,4}

Javascript regex validate password string (escaping punctuations)

I am trying to validate a password string with javascript and need some help with a regex. I have tried some tutorials, but I think I have some problems understanding how to escape quantifiers and/or metacharacters.
I want to make sure that the password string only contains one or more (max 32) characters from the following spans:
"abcdefghijklmnopqrstuvwxyz"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"012345678901234567890123456789"
"!##%&/(){}[]=?+*^~-_.:,;"
The first three spans are pretty easy, but I can't figure out the last one. Basically my script looks something like this:
var password = "user_input_password";
if (/^[A-Za-z0-9!##$%...]{1,32}$/.test(password)) {
document.write('OK');
} else {
document.write('Not OK');
}
Any help or input is highly appreciated, thanks!
In general, you can escape a meta-character using a backslash \; however, inside a character class, the only ones you have to escape are ] , \ and - (the ^ only has a meaning at the very beginning). Something like [\w!##%&/(){}[\]=?+*^~\-.:,;] will do what you want.
The \w is equal to [A-Za-z0-9_].
So the full test would be something like:
/^[\w!##%&/(){}[\]=?+*^~\-.:,;]{1,32}$/.test(password)
/^[A-Za-z0-9!##%&\/(){}\[\]=?+*^~\-_\.:,;]{1,32}$/
You can also match all characters that are not considered white space (space, newline, tab)
/^[^\s]{1,32}$/.test(password);
To exclude quotes as well (I didn't see them in your example) you can add those in:
/^[^\s'"]{1,32}$/.test(password);

Match a specific sequence or everything else with regex

Been trying to come up with a regex in JS that could split user input like :
"Hi{user,10,default} {foo,10,bar} Hello"
into:
["Hi","{user,10,default} ","{foo,10,bar} ","Hello"]
So far i achieved to split these strings with ({.+?,(?:.+?){2}})|([\w\d\s]+) but the second capturing group is too exclusive, as I want every character to be matched in this group. Tried (.+?) but of course it fails...
Ideas fellow regex gurus?
Here's the regex I came up with:
(:?[^\{])+|(:?\{.+?\})
Like the one above, it includes that space as a match.
Use this:
"Hi{user,10,default} {foo,10,bar} Hello".split(/(\{.*?\})/)
And you will get this
["Hi", "{user,10,default}", " ", "{foo,10,bar}", " Hello"]
Note: {.*?}. The question mark here ('?') stops at fist match of '}'.
Beeing no JavaScript expert, I would suggest the following:
get all positive matches using ({[^},]*,[^},]*,[^},]*?})
remove all positive matches from the original string
split up the remaining string
Allthough, this might get tricky if you need the resulting values in order.

Categories