validate username with regex in javascript - javascript

I am a newbie to regex and would like to create a regular expression to check usernames. These are the conditions:
username must have between 4 and 20 characters
username must not contain anything but letters a-z, digits 0-9 and special characters -._
the special characters -._ must not be used successively in order to avoid confusion
the username must not contain whitespaces
Examples
any.user.13 => valid
any..user13 => invalid (two dots successively)
anyuser => valid
any => invalid (too short)
anyuserthathasasupersuperlonglongname => invalid (too many characters)
any username => invalid because of the whitespace
I've tried to create my own regex and only got to the point where I specify the allowed characters:
[a-z0-9.-_]{4,20}
Unfortunately, it still matches a string if there's a whitespace in between and it's possible to have two special chars .-_ successively:
If anybody would be able to provide me with help on this issue, I would be extremely grateful. Please keep in mind that I'm a newbie on regex and still learning it. Therefore, an explanation of your regex would be great.
Thanks in advance :)

Sometimes writing a regular expression can be almost as challenging as finding a user name. But here you were quite close to make it work. I can point out three reasons why your attempt fails.
First of all, we need to match all of the input string, not just a part of it, because we don't want to ignore things like white spaces and other characters that appear in the input. For that, one will typically use the anchors ^ (match start) and $ (match end) respectively.
Another point is that we need to prevent two special characters to appear next to each other. This is best done with a negative lookahead.
Finally, I can see that the tool you are using to test your regex is adding the flags gmi, which is not what we want. Particularly, the i flag says that the regex should be case insensitive, so it should match capital letters like small ones. Remove that flag.
The final regex looks like this:
/^([a-z0-9]|[-._](?![-._])){4,20}$/
There is nothing really cryptic here, except maybe for the group [-._](?![-._]) which means any of -._ not followed by any of -._.

Related

Custom email regexp

I trying to create custom email regexp
[first]#[second].[third]
Allowed signs are numbers, letters and some special characters (I have done it)
One #
First+second to be from 1 to 20 characters long.
Email can't start or end with dot. Two or more dots next to each other are also not
allowed.
Third string to be 2 or 3 characters long.
This is what I have so far:
^(?!\.)(?=[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9]).{2,21}(?:\.[a-zA-Z0-9].{2,3})$
Unfortunately it doesn't work as I expected. Thanks for any tips.
For instance I can add multiple dots next to each other:
test...s#fm.com
Never ever write a regex to check for e-mails. You'll never make it right. As an example you say:
Allowed signs are numbers, letters and some special characters (I have done it)
which is terribly wrong, because you're then not including unicode characters like å or ţ which are valid. I'm also pretty sure you don't know that # is a valid value within the first part of an e-mail.
Third string to be 2 or 3 characters long.
and what about matching the following tlds: .info, .ninja, .website or .space?
So please, don't.
for reference:
https://davidcel.is/posts/stop-validating-email-addresses-with-regex/
http://stackoverflow.com/questions/23471591/regex-for-iban-allowing-for-white-spaces-and-checking-for-exact-length/23471740#23471740
http://thedailywtf.com/articles/how-to-validate-a-url
Following regex might help you.
^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,3}))$
Please read answer posted by #zmo too.

Identifying special non alphanumeric characters in a string

Im working on a password validation that should only allow a-z 0-9 and these characters "!"#$%&'()*+,-./:;<=>?#[\]^_{|}~`
I tried using a regex but I'm not too good with them and I wasnt sure if this is even possible or if Im not escaping the correct characters.
var allowedCharacters = /^[A-Za-Z0-9!"#$%&'()*+,-.\/:;<=>?#[\\]^_`{|}~]+$/;
if (!s.value.match(allowedCharacters)){
displayIllegalTextError();
return false;
}
You need to place the dash at the start or end of the regex, or it will try to create a character range (,-.). Then, a-Z isn't a valid range, you probably meant a-z. Also, you need to escape the closing brackets:
/^[A-Za-z0-9!"#$%&'()*+,.\/:;<=>?#[\\\]^_`{|}~-]+$/
Looking over the ascii chart here I see your regex could be reduced to this character range:
/^[\x21-\x7e]+$/
If you just want to learn special behavior of character classes, you should read up
on it via regex basic tutorials.
Note that class behavior differs amongst the different flavors.
Simpler and more to the point using unicode: ^[\u0021-\u007E]+$.
/^[\u0021-\u007E]+$/.test('MyPassword!') // returns true
/^[\u0021-\u007E]+$/.test('MyPassword™') // returns false
Now if you would like to go a few steps further and actually create a more complex validation such as: minimum length 8 characters and at least one lowercase, one uppercase, one digit and one special character:
^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[^a-zA-Z0-9])[\u0021-\u007E]{8,}$

What does this JavaScript Regular Expression /[^\d.-] mean?

We had a developer here who had added following line of code to a web application:
var amount = newValue.replace(/[^\d.-]/g, '');
The particular line deals with amount values that a user may enter into a field.
I know the following about the regular expression:
that it replaces the matches with empty strings (i.e. removes them)
that /g is a flag that means to match all occurrences inside "newValue"
that the brackets [] denote a special group
that ^ means beginning of the line
that d means digits
Unfortunately I do not know enough to determine what kind of strings this should match. I checked with some web-based regex testers if it matches e.g. strings like 98.- and other alternatives with numbers but so far no luck.
My problem is that it seems to make IE very slow so I need to replace it with something else.
Any help on this would be appreciated.
Edit:
Thanks to all who replied. I tried not just Google but sites like myregextester.com, regular-expressions.info, phpliveregex.com, and others. My problem was misunderstanding the meaning of ^ and expecting that this required a numeric string like 44.99.
Inside the group, when the ^ is the first character, it works as a negation of the character matches. In other words, it's saying match any character that are not the ones in the group.
So this will mean "match anything that is not a digit, a period, or a hyphen".
The ^ character is a negation character.
var newValue = " x44x.-x ";
var amount = newValue.replace(/[^\d.-]/g, '');
console.log(amount);
will print
44.-
I suspect the developer maybe just wanted to remove trailing whitespaces? I would rather try to parse the string for numbers and remove anything else.

JavaScript RegEx to allow only AlphaNumeric Characters and some special characters

In a textarea field, i want to allow only alphanumeric characters, -(hyphen),/(forward slash), .(dot) and space.
I have gone through similar questions but one way or the other, my exact requirements seem to differ. So, below is the regex i've come up with after reading answers give by members:
/^[a-z0-9\-\/. ]+$/i
I've tested the regex and so far it seems to work but i want to double check. Please verify as to whether the above regex fulfills my requirements.
You do too much escaping
/^[a-z0-9/. -]+$/i
In a character class, only [, ], \, - and ^ have special meaning, the ^ even only when it is the first character and the - only if it is between characters.
To match a literal ^ just put it into any position but the first. To match a - literally, don't put it between characters (i.e., at the start or at the end).
Escaping things like the /, . or $ is never necessary.

How to use javascript regex to check for "empty" form fields?

I am working on a php+javascript based project and have already made up a mockup page at :
my website
I knew how to use javascript or php to check whether a particular field of form is "empty"or not, that is, whether it contains alphanumerical characters other than whitepsace characters(for instance, space, tab and newline).
However, my normal apporach no longer works since the jquery plugin that I am using now relies on regex to validate the fields.
If you go to the third tab(3. Fill up Shipping Info and Make Payment), you can enter something into the Firstname field and it does the check automatically. Fine. However, if
you just simply put some space characters there and jump to the next field, well, it still feels okay for that, which is not correct since no one's first name is nothing!
The problem? At the back it has a regex like this :
"noSpecialCaracters":{
"regex":"/^[0-9a-zA-Z ]+$/",
"alertText":"* No special caracters allowed"},
This would not filter out empty characters.
I searched online and tried my best to make up another regex to match, I tried
"regex":"/^[^]+$/"
for matching non-empty characters, but that will not do...
Can anyone help me out? Many thanks in advance!
Try this for non-whitespace:
([^\s]*)
Example:
/([^\s])/.test(" A"); //TRUE
/([^\s])/.test(" "); //FALSE
function anyChar(str){
return /\S+/.test(str);
}
will return false if emty data
I'm using
/^\s*\S+.*/
which means
zero or more whitespace characters (\s*), followed by
one or more non-whitespace characters (\S+), followed by
anything at all, whitespace or not (.*).
This allows a single word or multiple words. I'm allowing whitespace at the beginning because I know how easy it is to miss a single space at the beginning and be really confused as to why your input isn't allowed :|
The Mozilla Developer Network has a great JavaScript regex page for reference.
You may want to try wrapping your expression in the following ^\s*(expression)\s*$. Then use the groups to find the "trimmed" matches. This eliminates only trailing or leading whitespace.
You can force the user to enter trimmed text or you can gracefully accept untrimmed input (better) as I find copying and pasting text often leaves some trailing or leading whitespace which the user may be unaware of.
To answer your question, the minimal regex is /\S/ which will match as long as there is at least one non-whitespace character.
However, you probably don't want someone to put in a first name of '12345' or '!!!', so it might be better to use /[a-z]/i as this regex will only match if there is at least one alphabetical character.
/^\s*[0-9a-zA-Z][0-9a-zA-Z ]*$/
that ensures that at least one character is not whitespace and is of one of the allowed characters.
You may also want to consider other characters like hyphen(-) or apostrophe(') that may also appear in names...
/^\s*[0-9a-zA-Z][0-9a-zA-Z '-]*$/

Categories