JS - Regex for name - javascript

The username should contain only alphabatic chars (a-z) up to 25 chars.
The first and the last space should be removed.
The username can be more then 1 word, not a limit for how many words the name counts
So the regex I am using now is almost valid, except that a username with 3 words or more isn't valid. And this should be valid.
Valid names can be:
Dennis
Dennis is
Dennis is cool
Dennis is the coolest
etc.. up to 25 chars because this is the max length.
This is the current regex I am using:
var pattern = /^[a-z\u00C0-\u01FF]+([\s\.\-\']?[a-z\u00C0-\u01FF]+)? $/i;
if (pattern.exec(uname) == null)
{
alert('Invalid name');
return false;
}
So how to adjust the regex to make it work for more words then 2 with a maximum length of 25 chars?

Your regex specifies it requires one set of characters, then optionally, a space and another set of characters. Hence your two word limit.
If you changed ([\s\.\-\']?[a-z\u00C0-\u01FF]+)? to ([\s\.\-\']?[a-z\u00C0-\u01FF]+)*, it would allow zero or more additional words, rather than zero or one.

Related

JavaScript RegEx, check if string contains * symbol and follows a set of specific rules [duplicate]

I want a regular expression to check that:
A password contains at least eight characters, including at least one number and includes both lower and uppercase letters and special characters, for example #, ?, !.
It cannot be your old password or contain your username, "password", or "websitename"
And here is my validation expression which is for eight characters including one uppercase letter, one lowercase letter, and one number or special character.
(?=^.{8,}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$"
How can I write it for a password must be eight characters including one uppercase letter, one special character and alphanumeric characters?
Minimum eight characters, at least one letter and one number:
"^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$"
Minimum eight characters, at least one letter, one number and one special character:
"^(?=.*[A-Za-z])(?=.*\d)(?=.*[#$!%*#?&])[A-Za-z\d#$!%*#?&]{8,}$"
Minimum eight characters, at least one uppercase letter, one lowercase letter and one number:
"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$"
Minimum eight characters, at least one uppercase letter, one lowercase letter, one number and one special character:
"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[#$!%*?&])[A-Za-z\d#$!%*?&]{8,}$"
Minimum eight and maximum 10 characters, at least one uppercase letter, one lowercase letter, one number and one special character:
"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[#$!%*?&])[A-Za-z\d#$!%*?&]{8,10}$"
You may use this regex with multiple lookahead assertions (conditions):
^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!#$%^&*-]).{8,}$
This regex will enforce these rules:
At least one upper case English letter, (?=.*?[A-Z])
At least one lower case English letter, (?=.*?[a-z])
At least one digit, (?=.*?[0-9])
At least one special character, (?=.*?[#?!#$%^&*-])
Minimum eight in length .{8,} (with the anchors)
Regular expressions don't have an AND operator, so it's pretty hard to write a regex that matches valid passwords, when validity is defined by something AND something else AND something else...
But, regular expressions do have an OR operator, so just apply DeMorgan's theorem, and write a regex that matches invalid passwords:
Anything with less than eight characters OR anything with no numbers OR anything with no uppercase OR or anything with no lowercase OR anything with no special characters.
So:
^(.{0,7}|[^0-9]*|[^A-Z]*|[^a-z]*|[a-zA-Z0-9]*)$
If anything matches that, then it's an invalid password.
Use the following Regex to satisfy the below conditions:
Conditions:
Min 1 uppercase letter.
Min 1 lowercase letter.
Min 1 special character.
Min 1 number.
Min 8 characters.
Max 30 characters.
Regex:
/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[#$#!%&*?])[A-Za-z\d#$#!%&*?]{8,30}$/
Just a small improvement for #anubhava's answer: Since special character are limited to the ones in the keyboard, use this for any special character:
^(?=.*?[A-Z])(?=(.*[a-z]){1,})(?=(.*[\d]){1,})(?=(.*[\W]){1,})(?!.*\s).{8,}$
This regex will enforce these rules:
At least one upper case English letter
At least one lower case English letter
At least one digit
At least one special character
Minimum eight in length
I had some difficulty following the most popular answer for my circumstances. For example, my validation was failing with characters such as ; or [. I was not interested in white-listing my special characters, so I instead leveraged [^\w\s] as a test - simply put - match non word characters (including numeric) and non white space characters. To summarize, here is what worked for me...
at least 8 characters
at least 1 numeric character
at least 1 lowercase letter
at least 1 uppercase letter
at least 1 special character
/^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[^\w\s]).{8,}$/
JSFiddle Link - simple demo covering various cases
 
✅ The following 4 regex patterns can help you to write almost any password validation
 
 
Pattern 1:
 
Password must contain one digit from 1 to 9, one lowercase letter, one uppercase letter, one special character, no space, and it must be 8-16 characters long.
/^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*\W)(?!.* ).{8,16}$/
 
Explanation:
 
(?=.*[0-9]) means that the password must contain a single digit from 1 to 9.
 
(?=.*[a-z]) means that the password must contain one lowercase letter.
 
(?=.*[A-Z]) means that the password must contain one uppercase letter.
 
(?=.*\W) means that the password must contain one special character.
 
.{8,16} means that the password must be 8-16 characters long. We must use this at the end of the regex, just before the $ symbol.
 
What are ^ and $:
 
^ indicates the beginning of the string. $ indicates the end of the string.
If we don't use these ^ & $, the regex will not be able to determine the maximum length of the password. In the above example, we have a condition that the password can't be longer than 16 characters, to make that condition work, we have used these ^ & $
 
Remove maximum length restriction:
 
Instead of .{8,16}, if we used .{8,}, it would mean that the password must be at least 8 characters long. So, there will not be any condition for checking the maximum length of the password.
 
Don't accept any number(digit):
 
Instead of (?=.*[0-9]), if we used (?!.*[0-9]), it would mean that the password must not contain any digit from 1-9 (Difference with the (?=.*[0-9]) is the use of ! instead of =)
 
Don't accept any spcecial character:
 
Instead of (?=.*\W), if we used (?!.*\W), it would mean that the password must not contain any special characters (The difference with the (?=.*\W) is the use of ! instead of =)
 
Alternative Syntax for number(digit):
 
Instead of (?=.*[0-9]), we could have used (?=.*\d). (?=.*\d) also means that the password must contain a single digit from 1 to 9.
 
 
Pattern 2:
 
Password must contain one digit from 1 to 9, one lowercase letter, one uppercase letter, one underscore but no other special character, no space and it must be 8-16 characters long.
/^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*_)(?!.*\W)(?!.* ).{8,16}$/
 
Difference with the Pattern 1
 
Here, we have used (?=.*_) which wasn't on the Pattern 1.
 
(?=.*_)(?!.*\W) means that the password must contain an underscore but can not contain any other special character.
 
Pattern 3:
 
Password must contain one digit from 1 to 9, one lowercase letter, one uppercase letter, one underscore, no space and it must be 8-16 characters long. Usage of any other special character other than underscore is optional.
/^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*_)(?!.* ).{8,16}$/
 
Difference with the Pattern 2
 
Here, we have not used (?!.*\W) what was on the Pattern 2.
 
But it still has the (?=.*_)
 
By just removing the (?!.*\W), special characters have become optional. Now, one underscore is required but any other special character can be used or not as it's optional.
 
Pattern 4:
 
Password must contain one digit from 1 to 9, one lowercase letter, one uppercase letter, and one underscore, and it must be 8-16 characters long. Usage of any other special character and usage of space is optional.
/^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).{8,16}$/
 
Difference with the Pattern 3
 
Here, we have not used (?=.*_) & (?!.* ) which was on the Pattern 3.
 
By removing (?=.*_), it's no longer mandatory to pass one underscore. Now, passing special characters is optional.
 
By removing the (?!.* ), usage of space has become optional too.
I would reply to Peter Mortensen, but I don't have enough reputation.
His expressions are perfect for each of the specified minimum requirements. The problem with his expressions that don't require special characters is that they also don't ALLOW special characters, so they also enforce maximum requirements, which I don't believe the OP requested. Normally you want to allow your users to make their password as strong as they want; why restrict strong passwords?
So, his "minimum eight characters, at least one letter and one number" expression:
^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$
achieves the minimum requirement, but the remaining characters can only be letter and numbers. To allow (but not require) special characters, you should use something like:
^(?=.*[A-Za-z])(?=.*\d).{8,}$ to allow any characters
or
^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d$#$!%*#?&]{8,}$ to allow specific special characters
Likewise, "minimum eight characters, at least one uppercase letter, one lowercase letter and one number:"
^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$
meets that minimum requirement, but only allows letters and numbers. Use:
^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$ to allow any characters
or
^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[A-Za-z\d$#$!%*?&]{8,} to allow specific special characters.
A more "generic" version(?), allowing none English letters as special characters.
^(?=\S*[a-z])(?=\S*[A-Z])(?=\S*\d)(?=\S*[^\w\s])\S{8,}$
var pwdList = [
'##V4-\3Z`zTzM{>k',
'12qw!"QW12',
'123qweASD!"#',
'1qA!"#$%&',
'Günther32',
'123456789',
'qweASD123',
'qweqQWEQWEqw',
'12qwAS!'
],
re = /^(?=\S*[a-z])(?=\S*[A-Z])(?=\S*\d)(?=\S*[^\w\s])\S{8,}$/;
pwdList.forEach(function (pw) {
document.write('<span style="color:'+ (re.test(pw) ? 'green':'red') + '">' + pw + '</span><br/>');
});
Import the JavaScript file jquery.validate.min.js.
You can use this method:
$.validator.addMethod("pwcheck", function (value) {
return /[\#\#\$\%\^\&\*\(\)\_\+\!]/.test(value) && /[a-z]/.test(value) && /[0-9]/.test(value) && /[A-Z]/.test(value)
});
At least one upper case English letter
At least one lower case English letter
At least one digit
At least one special character
For standard password requirements I found this to be useful:
At least 1 alphabet
At least 1 digit
Contains no space
Optional special characters e.g. #$!%*#?&^_-
Minimum 8 characters long
/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d#$!%*#?&^_-]{8,}$/
You can also set the upper limit for example {8,32} up to 32 characters long.
Try this one:
Minimum six characters
At least one uppercase character
At least one lowercase character
At least one special character
Expression:
"/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$#$!%*?&.])[A-Za-z\d$#$!%*?&.]{6, 20}/"
Optional Special Characters:
At least one special character
At least one number
Special characters are optional
Minimum six characters and maximum 16 characters
Expression:
"/^(?=.*\d)(?=.*[a-zA-Z]).{6,20}$/"
If the min and max condition is not required then remove .{6, 16}
6 is minimum character limit
20 is maximum character limit
?= means match expression
This worked for me:
^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[#$!%*?&])([a-zA-Z0-9#$!%*?&]{8,})$
At least 8 characters long;
One lowercase, one uppercase, one number and one special character;
No whitespaces.
Not directly answering the question, but does it really have to be a regex?
I used to do lots of Perl, and got used to solving problems with regexes. However, when they get more complicated with all the look-aheads and other quirks, you need to write dozens of unit tests to kill all those little bugs.
Furthermore, a regex is typically a few times slower than an imperative or a functional solution.
For example, the following (not very FP) Scala function solves the original question about three times faster than the regex of the most popular answer. What it does is also so clear that you don't need a unit test at all:
def validatePassword(password: String): Boolean = {
if (password.length < 8)
return false
var lower = false
var upper = false
var numbers = false
var special = false
password.foreach { c =>
if (c.isDigit) numbers = true
else if (c.isLower) lower = true
else if (c.isUpper) upper = true
else special = true
}
lower && upper && numbers && special
}
For a more strict validation where the following is required:
At least One Upper Case Character
At least one Lower Case character
At least one digit
At least one symbol/special character #$!%*#?&^_-
Minimum 8 characters/digits
Regex:
/(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[#$!%*#?&^_-]).{8,}/
I hope it helps someone with a more stringent.
What about considering the following regex solution:
^(?=.*[\w])(?=.*[\W])[\w\W]{8,}$
Which validates the following:
At least one lowercase
At least one uppercase
At least one digit
At least one special character
At least it should have 8 characters long.
Check it out working at the following link https://regex101.com/r/qPmC06/4/
^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[!##$%^&*()_+,.\\\/;':"-]).{8,}$
Another option is to make use of contrast in the lookahead assertions using a negated character class, optionally matching any character except that is listed before matching the character that should be matched.
^(?=[^A-Z\n]*[A-Z])(?=[^a-z\n]*[a-z])(?=[^0-9\n]*[0-9])(?=[^#?!#$%^&*\n-]*[#?!#$%^&*-]).{8,}$
See a regex demo
In parts, the pattern matches:
^ Start of string
(?=[^A-Z\n]*[A-Z]) Positive lookahead, assert 0+ times any char except A-Z or a newline. Then match a char A-Z
(?=[^a-z\n]*[a-z]) The same approach for a char a-z
(?=[^0-9\n]*[0-9]) The same approach for a digit 0-9
(?=[^#?!#$%^&*\n-]*[#?!#$%^&*-]) The same approach for a char that you would consider special
.{8,} Match 8 or more times any character except a newline
$ End of string
Notes
A dot can also match a space. If you do not want to allow matching a space, then .{8,} can be changed to \S{8,} to match 8 or more non whitespace characters
Using either . or \S can match more characters than are specified in the lookahead assertions. If you only want to match the characters that are used in the assertions, you can change .{8,} to match only the allowed characters [#?!#$%^&*A-Za-z0-9-]{8,} using a character class
const regex = /^(?=[^A-Z\n]*[A-Z])(?=[^a-z\n]*[a-z])(?=[^0-9\n]*[0-9])(?=[^#?!#$%^&*\n-]*[#?!#$%^&*-]).{8,}$/;
[
"abcA1#!A",
"#!asdfSFD1;",
"# a f F1 ;",
"1111111111",
"aaaaaaaa",
"11111111",
"AAAAAAAA",
"########",
"aA1#"
].forEach(s =>
console.log(regex.test(s) ? `Match --> ${s}` : `No match --> ${s}`)
);
/^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]).*$/
this the simple way to use it while validate atleast 1 uppercase 1 lowercase and 1 number
and this is the example while I use in express validation
check('password')
.notEmpty()
.withMessage('Password cannot be null')
.bail()
.isLength({ min: 6 })
.withMessage('Password must be at least 6 characters')
.bail()
.matches(/^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]).*$/)
.withMessage(
'Must have atleast 1 uppercase, 1 lowercase letter and 1 number'
),
Testing this one in 2020:
^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[#$!%*?&])[A-Za-z\d#$!%*?&]{8,}$
Verify yourself
const regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[#$!%*?&])[A-Za-z\d#$!%*?&]{8,}$/;
const str = `some12*Nuts`;
let m;
if ((m = regex.exec(str)) !== null) {
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
#ClasG has already suggested:
^(?=\S*[a-z])(?=\S*[A-Z])(?=\S*\d)(?=\S*[^\w\s])\S{8,}$
but it does not accept _(underscore) as a special character (eg. Aa12345_).
An improved one is:
^(?=\S*[a-z])(?=\S*[A-Z])(?=\S*\d)(?=\S*([^\w\s]|[_]))\S{8,}$
I've found many problems here, so I made my own.
Here it is in all it's glory, with tests:
^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*([^a-zA-Z\d\s])).{9,}$
https://regex101.com/r/DCRR65/4/tests
Things to look out for:
doesn't use \w because that includes _, which I'm testing for.
I've had lots of troubles matching symbols, without matching the end of the line.
Doesn't specify symbols specifically, this is also because different locales may have different symbols on their keyboards that they may want to use.
Demo:
function password_check() {
pass = document.getElementById("password").value;
console.log(pass);
regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[#$!%*?&])[A-Za-z\d#$!%*?&]{8,}$/;
if (regex.exec(pass) == null) {
alert('invalid password!')
}
else {
console.log("valid");
}
}
<input type="text" id="password" value="Sample#1">
<input type="button" id="submit" onclick="password_check()" value="submit">
var strongRegex = new RegExp("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!##\$%\^&\*])(?=.{8,})");
var mediumRegex = new RegExp("^(((?=.*[a-z])(?=.*[A-Z]))|((?=.*[a-z])(?=.*[0-9]))|((?=.*[A-Z])(?=.*[0-9])))(?=.{6,})");
Best For javascript
Keep it simple stupid:
This should do the trick for you, always.
Regex: ^(.{0,7}|[^a-z]{1,}|[^A-Z]{1,}|[^\d]{1,}|[^\W]{1,})$|[\s]
If your password matches the regex above, it is invalid.
If there's no match, your password is valid and contains has at least 8 characters, one upper case letter, one lower case letter and one symbol or special character. And it also contains no spaces, tabs or line breaks.
Breakdown of Regex
.{0,7} - matches if password has between 0 to 7 characters.
[^a-z]{1,} - matches if no lower case is found
[^A-Z]{1,} - matches if no upper case is found
[^\d]{1,} - matches if no number (between [0-9]) is found
[\s] - matches if a white space, tab or line break is found.
With this approach there's no limit or restriction in terms of symbols allowed. If you want to limit to few symbols allowable, just change [^\W] with [^YourSymbols].
(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[##$%^&+-]).{6}
According to your need this pattern should work just fine. Try this,
^(?=(.*\d){1})(.*\S)(?=.*[a-zA-Z\S])[0-9a-zA-Z\S]{8,}
Just create a string variable, assign the pattern, and create a boolean method which returns true if the pattern is correct, else false.
Sample:
String pattern = "^(?=(.*\d){1})(.*\S)(?=.*[a-zA-Z\S])[0-9a-zA-Z\S]{8,}";
String password_string = "Type the password here"
private boolean isValidPassword(String password_string) {
return password_string.matches(Constants.passwordPattern);
}
Use the following Regex to satisfy the below conditions:
Conditions: 1] Min 1 special character.
2] Min 1 number.
3] Min 8 characters or More
Regex: ^(?=.*\d)(?=.*[#$#!%&*?])[A-Za-z\d#$#!%&*?]{8,}$
Can Test Online: https://regex101.com
Just we can do this by using HTML5.
Use below code in pattern attribute,
pattern="(?=^.{8,}$)((?=.*\d)(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$"
It will work perfectly.
You can use the below regular expression pattern to check the password whether it matches your expectations or not.
((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[~!##$%^&*()]).{8,20})

javascript Regex to have atmost 5 characters in password

I am trying to implement maximum case in JavaScript for password validation.
I have a scenario where in password user should enter maximum 5 characters (a-z,A-Z) and password length having no restriction
Passsword length no limit
except (a-z,A-Z) ,there is no limtation
charcter(a-z,A-Z) will have atmost 5 in password .Not more than that.Sequence doesnot matter.
I tried /[^A-Z,a-z]*(?:[A-Z,a-z][^A-Z,a-z]*){0,5}/
But it is not working.
Kindly help
Did you even search? It is obviously, that this is a duplicate.
See
Regex javascript for Minimum 8 characters,at least one number and one special character, maximum 32 characters
Password REGEX with min 6 chars, at least one letter and one number and may contain special characters
JavaScript regex for alphanumeric string with length of 3-5 chars
You can just count how many characters you have in the password like so:
if(password.match(/[a-zA-Z]/g).length > 5){ /* reject */ }
You can use the below regex for password validation.
((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[##$%]).{5,20})
It validates :
Must contain ! digit [0-9]
One lowercase character [a-z]
One uppercase character [A-Z]
One symbol [##$%]
Length of password must be between [5-20].
Break it down and solve it step by step
Alphabet only - define your character set
/[A-Za-z]/
Maximum length of 5 - use a quantifier
/[A-Za-z]{0,5}/
Nothing else is allowed - wrap it with ^ and $
/^[A-Za-z]{0,5}$/

Check password valid using regex in javascript

The password must be eight characters or longer
The password must contain at least 2 lowercase alphabetical character.
The password must contain at least 2 uppercase alphabetical character.
The password must contain at least 2 numeric character.
The password must contain at least 2 special character.
My code
function checkPass(pw) {
var regx = new RegExp("^(?=.*[a-z]{2})(?=.*[A-Z]{2})(?=.*[0-9]{2})(?=.*[!##\$%\^&\*\)\(]{2})(?=.{8,})");
return regx.test(pw);
}
checkPass('PAssword12#$') => true
checkPass('PaSsword12#$') => false
I want to funtion return true when 2 uppercase character is not sequential.
Thanks!
You need to use the $ anchor to check for length (and best is to move that check out from lookaheads) and to allow some non-uppercase letters in between like this:
function checkPass(pw) {
var regx = /^(?=(?:[^a-z]*[a-z]){2})(?=(?:[^A-Z]*[A-Z]){2})(?=(?:\D*\d){2})(?=(?:[^!##$%^&*)(]*[!##$%^&*)(]){2}).{8,}$/;
return regx.test(pw);
}
document.write(checkPass('PAssword12#$') + "<br>");
document.write(checkPass('PaSsword12#$'));
Note that I used the principle of contrast: (?:[^a-z]*[a-z]){2} matches 2 sequences of symbols other than a-z zero or more times followed by 1 lowercase letter. I modified all the lookaheads the same way.
Rather than having [A-Z]{2} which will only match two uppercase characters together, you'll have to put in an optional match for any other characters in between two separate ranges (you'll have to do this for the lowercase, numbers and symbols as well). So you would instead put
[A-Z].*?[A-Z]
You also don't actually need to check whether it's at least 8 characters, because any password meeting the criteria for lowercase/uppercase letters, numbers and symbols has to be 8 characters at minimum anyway.

Javascript Regex - What to use to validate a phone number?

Could anyone tell me what RegEx would work to validate an international phone number including white space between the numbers and also allowing for these chars: - ( ).
The amount of numbers in the string is not too important, I would just like the user to be able to type something like either example 1 or 2 if they wish:
Example:
+44 (0) 207 111 1111
442071111111
I have already read through and tested the posted answers to some similar questions to the best of my understanding but so far none of them are working for me the way I want them to.
Please can someone help me out with a clear explanation of how the above should be written for validation?
Many thanks to anyone who can help.
Try this code
HTML Code
<input type="text" id="phone"/>
JS Code
$("#phone").blur(function() {
var regexp = /^[\s()+-]*([0-9][\s()+-]*){6,20}$/
var no = $("#phone").val();
if (!regexp.test(no) && no.length < 0) {
alert("Wrong phone no");
}
});
See A comprehensive regex for phone number validation
Quick cheat sheet
Start the expression: /^
If you want to require a space, use: [\s] or \s
If you want to require parenthesis, use: [(] and [)] . Using \( and \) is ugly and can make things confusing.
If you want anything to be optional, put a ? after it
If you want a hyphen, just type - or [-] . If you do not put it first or last in a series of other characters, though, you may need to escape it: \-
If you want to accept different choices in a slot, put brackets around the options: [-.\s] will require a hyphen, period, or space. A question mark after the last bracket will make all of those optional for that slot.
\d{3} : Requires a 3-digit number: 000-999. Shorthand for
[0-9][0-9][0-9].
[2-9] : Requires a digit 2-9 for that slot.
(\+|1\s)? : Accept a "plus" or a 1 and a space (pipe character, |, is "or"), and make it optional. The "plus" sign must be escaped.
If you want specific numbers to match a slot, enter them: [246] will require a 2, 4, or 6. [77|78] will require 77 or 78.
$/ : End the expression
This is a long regex, but it supports both formats (for example 2 to be a valid international number, is MUST start with either + or 00):
/^(?:(?:\(?(?:00|\+)([1-4]\d\d|[1-9]\d?)\)?)?[\-\.\ \\\/]?)?((?:\(?\d{1,}\)?[\-\.\ \\\/]?){0,})(?:[\-\.\ \\\/]?(?:#|ext\.?|extension|x)[\-\.\ \\\/]?(\d+))?$/i
This allows extensions and a multiple choice of formats and separators.
Matches:
(+351) 282 43 50 50
90191919908
555-8909
001 6867684
001 6867684x1
1 (234) 567-8901
1-234-567-8901 x1234
1-234-567-8901 ext1234
1-234 567.89/01 ext.1234
1(234)5678901x1234
(123)8575973
(0055)(123)8575973
On $n, it saves:
Country indicator
Phone number
Extention
This same answer was given here: A comprehensive regex for phone number validation (direct link to my answer)
/*
#isValidUSPhoneFormat function will check valid US Format
Allowed US Format
(123) 456-7890
123-456-7890
123.456.7890
1234567890
(734) 555.1212
*/
function isValidUSPhoneFormat(elementValue){
var phoneNumberPattern = /^[(]{0,1}[0-9]{3}[)]{0,1}[-\s.]{0,1}[0-9]{3}[-\s.]{0,1}[0-9]{4}$/;
if(phoneNumberPattern.test(elementValue) == false)
{
var phoneNumberPattern = /^(\()?\d{3}(\))?(.|\s)?\d{3}(.|\s)\d{4}$/;
return phoneNumberPattern.test(elementValue);
}
return phoneNumberPattern.test(elementValue);
}
May this will help you to understand JavaScript RegEx..
Don't even try. Trying to guard against what you think is invalid input can result in angry users who can't enter perfectly valid phone numbers. And if the user really wants to enter an invalid phone number, he/she will be able to do it anyway.
function checkPhoneNumber(val) {
var num = document.getElementById(val).value;
var mob=/^[+]*[(]{0,1}[0-9]{1,3}[)]{0,1}[-\s\./0-9]*$/g;
if (mob.test(num) == false) {
alert("Please Enter Valid Phone Number.");
document.getElementById(val).value = "";
return false;
}
if (num.length > 15) {
alert("Only 15 characters allowed for Phone Number field.");
document.getElementById(val).value = "";
return false;
}
return true;
}
Try it Ones
Try using isValidPhoneNumber(phoneNumber, countryCode) method of libphonenumber-js package. First is the phone number with "+" at the start of it. The second argument is the country code (for eg: 'US', 'IN'). That helps you validate any international number accurately.
Best lib for international phone number: google/libphonenumber
Here is an example with CDN:
<script src="https://cdn.jsdelivr.net/npm/google-libphonenumber#3/dist/libphonenumber.min.js"></script>
// Format Phone Number
function formatPhone(p) {
var phoneUtil = libphonenumber.PhoneNumberUtil.getInstance();
var parsedPhone = phoneUtil.parse(p);
if (phoneUtil.isValidNumber(parsedPhone)) {
return phoneUtil.format(parsedPhone, libphonenumber.PhoneNumberFormat.INTERNATIONAL)
} else {
return NaN
}
}
A better option to validate international phone numbers in a loose way is as follows.This is not a strict validation
/^\s*(?:+?(\d{1,3}))?([-. (](\d{3})[-. )])?((\d{3})[-. ](\d{2,4})(?:[-.x ](\d+))?)\s*$/gm
A working Javascript function will look like this
function validatePhone(phone) {
var regex = /^\s*(?:\+?(\d{1,3}))?([-. (]*(\d{3})[-. )]*)?((\d{3})[-. ]*(\d{2,4})(?:[-.x ]*(\d+))?)\s*$/gm;
return regex.test(phone);
}
console.log(validatePhone('+973 11111111')) // true
console.log(validatePhone('+973 XX77yyss')) // false
For those who wish to have more about the characters:
^ asserts position at the start of a line
\s matches any whitespace character (equivalent to [\r\n\t\f\v ])
* matches the previous token between zero and unlimited times, as many times as possible, giving back as needed (greedy)
Non-capturing group (?:+?(\d{1,3}))?
? matches the previous token between zero and one times, as many times as possible, giving back as needed (greedy)
+ matches the character + with index 4310 (2B16 or 538) literally (case sensitive)
? matches the previous token between zero and one times, as many times as possible, giving back as needed (greedy) 1st Capturing
Group (\d{1,3})
\d matches a digit (equivalent to [0-9])
{1,3} matches the previous token between 1 and 3 times, as many times as possible, giving back as needed (greedy) 2nd Capturing
Group ([-. (](\d{3})[-. )])?
? matches the previous token between zero and one times, as many times as possible, giving back as needed (greedy) Match a single
character present in the list below [-. (]
* matches the previous token between zero and unlimited times, as many times as possible, giving back as needed (greedy)
-. ( matches a single character in the list -. ( (case sensitive) 3rd Capturing Group (\d{3})
\d matches a digit (equivalent to [0-9])
{3} matches the previous token exactly 3 times Match a single character present in the list below [-. )]
* matches the previous token between zero and unlimited times, as many times as possible, giving back as needed (greedy)
-. ) matches a single character in the list -. ) (case sensitive) 4th Capturing Group ((\d{3})[-. ](\d{2,4})(?:[-.x
](\d+))?) 5th Capturing Group (\d{3})
\d matches a digit (equivalent to [0-9])
{3} matches the previous token exactly 3 times Match a single character present in the list below [-. ]
* matches the previous token between zero and unlimited times, as many times as possible, giving back as needed (greedy)
-. matches a single character in the list -. (case sensitive) 6th Capturing Group (\d{2,4})
\d matches a digit (equivalent to [0-9])
{2,4} matches the previous token between 2 and 4 times, as many times as possible, giving back as needed (greedy) Non-capturing
group (?:[-.x ]*(\d+))?
? matches the previous token between zero and one times, as many times as possible, giving back as needed (greedy) Match a single
character present in the list below [-.x ]
* matches the previous token between zero and unlimited times, as many times as possible, giving back as needed (greedy)
-.x matches a single character in the list -.x (case sensitive) 7th Capturing Group (\d+)
\d matches a digit (equivalent to [0-9])
+ matches the previous token between one and unlimited times, as many times as possible, giving back as needed (greedy)
\s matches any whitespace character (equivalent to [\r\n\t\f\v ])
* matches the previous token between zero and unlimited times, as many times as possible, giving back as needed (greedy)
$ asserts position at the end of a line
This would test positive for the below patterns and more
+42 555.123.4567 +1-(800)-123-4567 +7 555 1234567 +7(926)1234567 (926) 1234567 +79261234567 926 1234567 9261234567 1234567 123-4567 123-89-01 495 123

Password REGEX with min 6 chars, at least one letter and one number and may contain special characters

I need a regular expression with condition:
min 6 characters, max 50 characters
must contain 1 letter
must contain 1 number
may contain special characters like !##$%^&*()_+
Currently I have pattern: (?!^[0-9]*$)(?!^[a-zA-Z]*$)^([a-zA-Z0-9]{6,50})$
However it doesn't allow special characters, does anybody have a good regex for that?
Thanks
Perhaps a single regex could be used, but that makes it hard to give the user feedback for which rule they aren't following. A more traditional approach like this gives you feedback that you can use in the UI to tell the user what pwd rule is not being met:
function checkPwd(str) {
if (str.length < 6) {
return("too_short");
} else if (str.length > 50) {
return("too_long");
} else if (str.search(/\d/) == -1) {
return("no_num");
} else if (str.search(/[a-zA-Z]/) == -1) {
return("no_letter");
} else if (str.search(/[^a-zA-Z0-9\!\#\#\$\%\^\&\*\(\)\_\+]/) != -1) {
return("bad_char");
}
return("ok");
}
following jfriend00 answer i wrote this fiddle to test his solution with some little changes to make it more visual:
http://jsfiddle.net/9RB49/1/
and this is the code:
checkPwd = function() {
var str = document.getElementById('pass').value;
if (str.length < 6) {
alert("too_short");
return("too_short");
} else if (str.length > 50) {
alert("too_long");
return("too_long");
} else if (str.search(/\d/) == -1) {
alert("no_num");
return("no_num");
} else if (str.search(/[a-zA-Z]/) == -1) {
alert("no_letter");
return("no_letter");
} else if (str.search(/[^a-zA-Z0-9\!\#\#\$\%\^\&\*\(\)\_\+\.\,\;\:]/) != -1) {
alert("bad_char");
return("bad_char");
}
alert("oukey!!");
return("ok");
}
btw, its working like a charm! ;)
best regards and thanks to jfriend00 of course!
Check a password between 7 to 16 characters which contain only characters, numeric digits, underscore and first character must be a letter-
/^[A-Za-z]\w{7,14}$/
Check a password between 6 to 20 characters which contain at least one numeric digit, one uppercase, and one lowercase letter
/^(?=.\d)(?=.[a-z])(?=.*[A-Z]).{6,20}$/
Check a password between 7 to 15 characters which contain at least one numeric digit and a special character
/^(?=.[0-9])(?=.[!##$%^&])[a-zA-Z0-9!##$%^&]{7,15}$/
Check a password between 8 to 15 characters which contain at least one lowercase letter, one uppercase letter, one numeric digit, and one special character
/^(?=.\d)(?=.[a-z])(?=.[A-Z])(?=.[^a-zA-Z0-9])(?!.*\s).{8,15}$/
I hope this will help someone. For more please check this article and this site regexr.com
A more elegant and self-contained regex to match these (common) password requirements is:
^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d^a-zA-Z0-9].{5,50}$
The elegant touch here is that you don't have to hard-code symbols such as $ # # etc.
To accept all the symbols, you are simply saying: "accept also all the not alphanumeric characters and not numbers".
Min and Max number of characters requirement
The final part of the regex {5,50} is the min and max number of characters, if the password is less than 6 or more than 50 characters entered the regex returns a non match.
I have a regex, but it's a bit tricky.
^(?:(?<Numbers>[0-9]{1})|(?<Alpha>[a-zA-Z]{1})|(?<Special>[^a-zA-Z0-9]{1})){6,50}$
Let me explain it and how to check if the tested password is correct:
There are three named groups in the regex.
1) "Numbers": will match a single number in the string.
2) "Alpha": will match a single character from "a" to "z" or "A" to "Z"
3) "Special": will match a single character not being "Alpha" or "Numbers"
Those three named groups are grouped in an alternative group, and {6,50} advises regex machine to capture at least 6 of those groups mentiond above, but not more than 50.
To ensure a correct password is entered you have to check if there is a match, and after that, if the matched groups are capture as much as you desired. I'm a C# developer and don't know, how it works in javascript, but in C# you would have to check:
match.Groups["Numbers"].Captures.Count > 1
Hopefully it works the same in javascript! Good luck!
I use this
export const validatePassword = password => {
const re = /^(?=.*[A-Za-z])(?=.*\d)[a-zA-Z0-9!##$%^&*()~¥=_+}{":;'?/>.<,`\-\|\[\]]{6,50}$/
return re.test(password)
}
DEMO https://jsfiddle.net/ssuryar/bjuhkt09/
Onkeypress the function triggerred.
HTML
<form>
<input type="text" name="testpwd" id="testpwd" class="form=control" onkeyup="checksPassword(this.value)"/>
<input type="submit" value="Submit" /><br />
<span class="error_message spassword_error" style="display: none;">Enter minimum 8 chars with atleast 1 number, lower, upper & special(##$%&!-_&) char.</span>
</form>
Script
function checksPassword(password){
var pattern = /^.*(?=.{8,20})(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[##$%&!-_]).*$/;
if(!pattern.test(password)) {
$(".spassword_error").show();
}else
{
$(".spassword_error").hide();
}
}
International UTF-8
None of the solutions here allow international letters, i.e. éÉöÖæÆóÓúÚáÁ, but are mainly focused on the english alphabet.
The following regEx uses unicode, UTF-8, to recognise upper and lower case and thus, allow international characters:
// Match uppercase, lowercase, digit or #$!%*?& and make sure the length is 6 to 50 in length
const pwdFilter = /^(?=.*\p{Ll})(?=.*\p{Lu})(?=.*[\d|##$!%*?&])[\p{L}\d##$!%*?&]{6,50}$/gmu
if (!pwdFilter.test(pwd)) {
// Show error that password has to be adjusted to match criteria
}
This regEx
/^(?=.*\p{Ll})(?=.*\p{Lu})(?=.*[\d|##$!%*?&])[\p{L}\d##$!%*?&]{6,50}$/gmu
checks if an uppercase, lowercase, digit or #$!%*?& are used in the password. It also limits the length to be 6 minimum and maximum 50 (note that the length of 😀🇺🇸🇪🇸🧑‍💻 emojis counts as more than one character in the length).
The u in the end, tells it to use UTF-8.
First, we should make the assumption that passwords are always hashed (right? always hashed, right?). That means we should not specify the exact characters allowed (as per the 4th bullet). Rather, any characters should be accepted, and then validate on minimum length and complexity (must contain a letter and a number, for example). And since it will definitely be hashed, we have no concerns over a max length, and should be able to eliminate that as a requirement.
I agree that often this won't be done as a single regex but rather a series of small regex to validate against because we may want to indicate to the user what they need to update, rather than just rejecting outright as an invalid password. Here's some options:
As discussed above - 1 number, 1 letter (upper or lower case) and min 8 char. Added a second option that disallows leading/trailing spaces (avoid potential issues with pasting with extra white space, for example).
^(?=.*\d)(?=.*[a-zA-Z]).{8,}$
^(?=.*\d)(?=.*[a-zA-Z])\S.{6,}\S$
Lastly, if you want to require 1 number and both 1 uppercase and 1 lowercase letter, something like this would work (with or without allowing leading/trailing spaces)
^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}$
^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])\S.{6,}\S$
Lastly as requested in the original post (again, don't do this, please try and push back on the requirements!!) - 1 number, 1 letter (upper or lower case), 1 special char (in list) and min 8 char, max 50 char. Both with/without allowing leading/trailing spaces, note the min/max change to account for the 2 non-whitespace characters specified.
^(?=.*\d)(?=.*[a-zA-Z])(?=.*[!##$%^&*()_+]).{8,50}$
^(?=.*\d)(?=.*[a-zA-Z])(?=.*[!##$%^&*()_+])\S.{6,48}\S$
Bonus - separated out is pretty simple, just test against each of the following and show the appropriate error in turn:
/^.{8,}$/ // at least 8 char; ( /^.{8,50}$/ if you must add a max)
/[A-Za-z]/ // one letter
/[A-Z]/ // (optional) - one uppercase letter
/[a-z]/ // (optional) - one lowercase letter
/\d/ // one number
/^\S+.*\S+$/ // (optional) first and last character are non-whitespace)
Note, in these regexes, the char set for a letter is the standard English 26 character alphabet without any accented characters. But my hope is this has enough variations so folks can adapt from here as needed.
// more secure regex password must be :
// more than 8 chars
// at least one number
// at least one special character
const PASSWORD_REGEX_3 = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!##$%^&*]).{8,}$/;

Categories