Alphanumeric JavaScript RegEx for Password Validation - javascript

I'm using a regex below to validate password to accept alphanumeric characters only. The regex works if I enter 2 characters one alpha and one number but if more than two characters my regex doesn't work. I want if possible the following results as shown in "Expected Behavior". Can anyone help me rewrite my regex?
JavaScript
function checkPasswordComplexity(pwd) {
var regularExpression = /^[a-zA-Z][0-9]$/;
var valid = regularExpression.test(pwd);
return valid;
}
Current Behavior
Password:Valid
a1:true
aa1:false
aa11:false
Expected Behavior
Password:Valid
aa:false (should have at least 1 number)
1111111:false (should have at least 1 letter)
aa1:true
aa11:true
a1a1a1a1111:true

You want to add "one or more", you're currently checking for a letter followed by a number.
Try:
/^[a-zA-Z0-9]+$/
+ means 'one or more'
I also joined the ranges.
Note: I don't understand why you'd want to limit the password to such a small range though, having a wide character range will make your passwords stronger.
Here is a fiddle demonstrating the correct behavior
If you just want to validate that the password has at least one letter and at least one number, you can check like this:
function checkPasswordComplexity(pwd) {
var letter = /[a-zA-Z]/;
var number = /[0-9]/;
var valid = number.test(pwd) && letter.test(pwd); //match a letter _and_ a number
return valid;
}

function checkPasswordComplexity(pwd) {
var regularExpression = /^(?=.*[0-9])(?=.*[a-zA-Z])([a-zA-Z0-9]+)$/;
var valid = regularExpression.test(pwd);
return valid;
}

You can use this:
/^(?=.*\d)(?=.*[a-z])[a-z\d]{2,}$/i

Try doing this:
var regularExpression = /^[a-zA-Z0-9]+$/;
This means "one or more letter or number."
However, some users might also want to enter symbols (like &*#) in their passwords. If you just want to make sure there is at least one letter and number while still allowing symbols, try something like this:
var regularExpression = /^(?=.*[a-zA-Z])(?=.*[0-9]).+$/;
The (?=.*[a-zA-Z]) is a positive lookahead. This means that it makes sure that there is a letter ahead of it, but it doesn't affect the regex.

{
var pwd=document.getElementById('pwd').value;
var reg = /^[a-zA-Z0-9]{8,}$/;
var re=reg.test(pwd);
alert(re);
}

I think lookaround aren't supported by javascript, so you can use:
^([a-zA-Z]+\d+)|(\d+[a-zA-Z]+)
But if they are supported:
/^(?=.*\d)(?=.*[a-zA-Z])[a-zA-Z\d]{2,}$/

Related

Regex: Check input string is not only upperccase and is not only lowercase

What is the regex to check if input string is NOT lowercase only, it is NOT uppercase only and does NOT contain numbers.
Validation must fail
SIMO TEST
SIMO344
simo
simo3432
These are ok
SIMO test
Simo
Welcome to Stackoverflow
When posting a question, please make sure to include your attempts, so that we can help guide you to an answer. This website is not meant to give you the answer, but to help guide you to an answer, or to explain your error. It's more rewarding to help you if we are simply guiding you and not giving you the answer. You'll probably get more response too. Please remember that when posting next time.
I tried to explain regular expressions in JavaScript, and tried to guide you through the logic in my answer.
Your case
You can use the .test function of a RegExp to test if a string matches a regular expression. You can then invert that result to check if the string does not contain it. Each of the cases you mentioned is a separate expression, which can be joined by the | operator.
Testing if a string is lowercase only:
In a RegExp, a - can be used to indicate a range of characters. There are already specially assigned codes for commonly used ranges, such as \s for a white space. The + operator means one or more. The ^ means starts at the beginning of the line(string) and $ means starting the end.
^[a-z\s]+$
Testing if a string is uppercase only:
This is the exact same as the lowercase case, but the character range is for uppercase letters:
^[A-Z\s]+$
Testing for digits
The regex code \d is short for a range of digits (you can essentially think of it as [0-9], but it also accounts for unicode).
\d
Putting it all together
^[a-z\s]+$|^[A-Z\s]+$|\d
And in a condition, it would be:
if (!/^[a-z\s]+$|^[A-Z\s]+$|\d/.test(your_string_here)) {
// the string isn't uppercase only, lowercase only
// and doesn't contain a digit
}
Please see the below code snippet. Modify as per your requirement.
function validate(strInput) {
var re = /\d/;
if(re.exec(strInput)===null){
re = /^(?!.*[a-z\d]).+$/;
if(re.exec(strInput)===null){
re = /^[A-Z][a-z]*/;
if(re.exec(strInput)!==null)
return re.exec(strInput);
}
}
return false;
};
console.log(validate("SIMO TEST"));
console.log(validate("SIMO344"));
console.log(validate("Simo"));
console.log(validate("simo"));
console.log(validate("simo3432"));
console.log(validate("SIMO2 TEST"));
console.log(validate("Simo3"));
console.log(validate("SIMO test"));
function CheckPassword() {
var inputtxt = $('#text12').val();
console.log(inputtxt)
var passw = /(?=.*[a-z])(?=.*[A-Z]).{6,20}$/;
var passWN = /\d/;
if (inputtxt.match(passw)) {
if (!inputtxt.match(passWN)) {
alert('Correct, try another...')
return true;
} else {
alert('Wrong...!')
return false;
}
} else {
alert('Wrong...!')
return false;
}
}

Javascript Regex doesn't match with my String

I have the following String :
var resultLine= "[UT] - GSM incoming call : STEP 1 - Simulate reception from server (1)Rerun3713 msAssertion ok"
And the following code which is responsible to check of the String matched with the Regex :
var resultRE = /^([ \w-]*: )?(.+) \((\d+), (\d+), (\d+)\)Rerun/;
var resultMatch = resultLine.match(resultRE);
if (resultMatch) {
return true;
} else {
return false;
}
In this case, i have an error in my Regex because i always get "false".
Where is my mistake ?
I would recommend the following pattern based on what it appears you are looking for:
var resultRE = /^([\[ \w\]-]*: )(.+) \(([0-9, ]*)\)Rerun(.*)$/
This should force all capture groups to exist, even if they are empty, and will allow for multiple numbers before Rerun as you seem to expect.
This matches nothing in your string
([ \w-]*: )?
Since it was optional, that doesn't matter because it gets caught by the all inclusive
(.+)
If you were trying to match the [UT] part with it's separator, it would look something like this
(\[\w+\][\s\-]*)?
As noted in the comments, you only have one number in parentheses but your regex requires three sets of them, separated by commas. This will allow any number of numbers, separated by commas indefinitely (I don't know if there's a limit or not).
\((\d+,\s)*(\d+)\)
If you need something more specific, you'll have to be more specific about what template your matching, not a specific case. But the best I can figure with what you've provided is
^(\[\w\][\s\-]*)?(.+)\((\d+,\w)*(\d+)\)Rerun
var resultRE = /\((\d+)(?:, (\d+))?(?:, (\d+))?\)Rerun/;
if (resultRE.test(resultLine)) {
var num1 = RegExp.$1,
num2 = RegExp.$2,
num3 = RegExp.$3;
}

regular expression to validate a password javascript

I need a regular expression to validate a password containing at least 8 characters, must include at least one uppercase letter and a lowercase letter. And must specifically include one of the following symbols #,#,%,^,&,*,)
i havent been able to find one that would include only those ascii characters.
thanks in advance for your help!
/^(?=.*[a-z])(?=.*[A-Z])(?=.*[!##$%^&*]).{8,}$/
Regular expression to assert a password that must contain atleast one Smallcase ,Capitalcase alphabet and a Special character(!##$%^&*).
Can increase the max length of password from 20 to more.
You can also put all your validation regex's in an array and then use every.
var atLeastLowerCase = /[a-z]/;
var atLeastUpperCase = /[A-Z]/;
var atLeastSpecial = /[\#\#\%\^\&\*\]\)]/;
var password = "somePass#";
var passes = [atLeast8,atLeastLowerCase,atLeastUpperCase,atLeastSpecial].every(function(a){
return a.test(password);
}) && password.length>=8;
if(passes){
//do something
}else{
//do something else
}

Regular expression for multiple email addresses

I am working to validate a string of email addresses. This pattern works fine if there is only one email address:
var pattern = /^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
But if I have two email addresses separated by space or by a newline, then it does not validate. For example:
xyz#abc.com xyz#bbc.com
or
xyz#abc.com
xyz#bbc.com
Can you please tell me what would be a way to do it? I am new to regular expressions.
Help much appreciated! Thanks.
Try this RegEx
/^\s*(?:\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}\b\s*)+$/
In the above image, everything inside Group 1 is what you already had. I have added a word ending and spaces.
It will match "xyz#abc.com", " xyz#bbc.com ", "xyz#abc.com xyz#bbc.com" and email addresses in multiple lines also.
Update
I got the RegEx for Email from http://www.regular-expressions.info/email.html and I have used it in my expression. You can find it below:
/^\s*(?:([A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4})\b\s*)+$/i
Change the ^ and $ anchors to word boundaries, \b.
/\b\w+...{2,3}\b/
You should also note that the actual specification for email addresses is extremely complicated and there are many emails that will fail this test -- for example those with multiple periods in the domain. May be okay for your purposes, but just pointing it out.
try this
function validateEmail(field) {
var regex=/\b[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\b/i;
return (regex.test(field)) ? true : false;
}
function validateMultipleEmailsCommaSeparated(value) {
var result = value.split(" ");
for(var i = 0;i < result.length;i++)
if(!validateEmail(result[i]))
return false;
return true;
}
You might consider simply splitting the whole string into an actual array of email addresses, instead of trying to validate the entire thing at once. This has the advantage of allowing you to point out in your validation message which address failed.
uld look like this:
var emailRegex = /^[A-Z0-9._%+-]+#(?:[A-Z0-9-]+\.)+[A-Z]{2,4}$/i; // http://www.regular-expressions.info/email.html
var split = form.emails.value.split(/[\s;,]+/); // split on any combination of whitespace, comma, or semi-colon
for(i in split)
{
email = split[i];
if(!emailRegex.test(email))
{
errMsg += "The to e-mail address ("+email+") is invalid.\n";
}
}
Your best regular expression for multiple emails accepts all special characters
(-*/+;.,<>}{[]||+_!##$%^&*())
Best Regular Expression for multiple emails
/^([A-Z0-9.%+-]+#[A-Z0-9.-]+.[A-Z]{2,6})*([,;][\s]*([A-Z0-9.%+-]+#[A-Z0-9.-]+.[A-Z]{2,6}))*$/i

Allow only lowercase characters

I use following code to check if a user input is lowercase or not. I will allow characters from a to z. no other characters allowed.
JavaScript file:
var pat = /[a-z]/;
function checkname()
{
var t = $("input[name='user_name']").val();
if(pat.test(t) == false)
{
alert('Only lowercase characters allowed');
}
}
//... other functions
But this donot work all the time. If I enter industrialS, it will not find that capital 'S'.
I also tried: /^[a-z]$/ and /[a-z]+/. But not working.
PLease help me.
Your regular expression just checks to see if the string has any lower-case characters. Try this:
var pat = /^[a-z]+$/;
That pattern will only match strings that have one or more lower-case alphabetic characters, and no other characters. The "^" at the beginning and the "$" at the end are anchors that match the beginning and end of the tested string.
if((/[a-z]/.test(email))==true){//allow the small characters}
Your regexp should be:
/^[a-z]+$/
Since all you want is lower case letters, instead of just telling the user s/he's done something wrong, I would fix it:
function checkname() {
var disallowed = /[^a-z]/gi; // g=global , i=case-insensitive
if (this.value == disallowed) {
//delete disallowed characters
this.value = this.value.replace(disallowed,'');
alert('Only lowercase letters allowed');
//instead of an alert, i would use a less intrusive fadeIn() message
}
this.value = this.value.toLowerCase();
}

Categories