Regular Expression in Javascript for password validation - javascript

I am trying to create a regular expression that validates a user's password when they create it. The password needs to be:
at least 6 characters long and can be any type of character
each character that is used needs to appear in the password exactly 3 times.
Good examples:
AAABBB
ABABBA
+++===
+ar++arra
myyymm
/Arrr/AA/
Does anyone know which regex would accomplish this?

You can ease yourself by sorting the password before testing it:
$('button').on('click', function(){
var s = $('#password').val();
var split = s.split("").sort().join("");
if(/^(?:(.)\1{2}(?!\1)){2,}$/.test(split))
console.log("Valid password");
else
console.log("Invalid password");
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input id="password">
<button>Test me</button>

For 1st option you have to check without regex.
var str = "your password";
var pattern = /(.)(.*\1){3}/;
if(str.length >= 6){
// It will give you boolean as return
// If it is match then it return true else false
pattern.test(str);
}

An alternative solution since you're allowing code (which your question imply you wouldn't ;)
Using a function like verifyPass below should do the trick. It gradually replaces any valid three letter combination with an empty string. Checking that this is done in more than one iteration (it's at least 6 characters) and ending up with an empty string in the end, means it's a valid password.
function verifyPass(pass) {
var re = /^(.)((?:(?!\1).)*)\1((?:(?!\1).)*)\1((?:(?!\1).)*)$/,
cnt=0;
while(re.test(pass)) {
pass = pass.replace(re, '$2$3$4');
cnt++;
}
return pass==='' && cnt>1;
}
var testItems = [
'123123123',
'AAABBB',
'AAABBBAAA',
'Qwerty',
'ABABBA',
'+++===',
'111',
'qweqwd',
'sdcjhsdfkj',
'+ar++arra',
'mYYYmms',
'/Arrr/AA/'
];
testItems.forEach(function(item) {
document.write('<span style="color:' + (verifyPass(item) ? 'green' : 'red') + ';">' + item + '</span> <br/>');
});

Related

how to pass the json data inside javascript regex? and also validate password in sequence

I am trying to validate the password using javascript regex. Now I want to validate two lower case letters (2 small letters) which is coming from json.
psw.onkeyup = function() {
var Lcase = jsonData.LOWERCASE;
var psw = document.getElementById("password");
var lowerCaseLetters = /[a-z]{2}/g;
if(psw.value.match(lowerCaseLetters)) {
letter.classList.remove("invalid");
letter.classList.add("valid");
} else {
letter.classList.remove("valid");
letter.classList.add("invalid");
}
}
In the above code I am setting up a variable "Lcase" to json data and now I want to replace "{2}" (inside regex) with that variable "Lcase" coz the "Lcase" variable is dynamic. If I am doing something wrong then please guide me to come out of this problem.
I want to validate small case letters which is coming from json(dynamic number) to see how many small letters are there in the password string.
For your information the below code for password length is working.
if(psw.value.length >= jsonData.MINLEN_RANGE) {
length.classList.remove("invalid");
length.classList.add("valid");
} else {
length.classList.remove("valid");
length.classList.add("invalid");
}
If define your regular expression using RegExp, you can define {2} using Lcase.
This code also includes the question posted on the comments bellow.
psw.onkeyup = function() {
var Lcase = jsonData.LOWERCASE;
var psw = document.getElementById("password").value.replace(/([a-z])\d+/g, '$1');
var lowerCaseLetters = new RegExp('[a-z]{' + Lcase + '}', 'g')
if(psw.match(lowerCaseLetters)) {
letter.classList.remove("invalid");
letter.classList.add("valid");
} else {
letter.classList.remove("valid");
letter.classList.add("invalid");
}
}

How can I get my span id’s to display the appropriate messages when user doesn’t follow rules?

I am currently having problems with displaying different span error messages for some of the same input texboxes based on if the user doesn't follow my validation rules. I really could use some suggestions of how I can make some of my if statements better to enforce my rules that I have setup. I am okay with how my if statement is validating the username and how if statement is validating the password, but I have been struggling to try to figure what is the best method for validating my repeatemail textbox and emailaddress textbox. Can someone help me? Thanks in advance! Here is my HTML, CSS, and JavaScript/JQuery code
$('#button2').on('click', function () {
var NewUsernameError = document.getElementById("New_Username_error");
var NewPasswordError = document.getElementById("New_Password_error");
var NewEmailAddressError = document.getElementById("New_Email_error");
// var NewRepeatEmailAddressError=document.getElementById("NewReenter_Email_error");
// How can I get my span id's to display one of two different error //messages based on my rules below? Right now it will only display first error //messages. Do I need to create two different span ids (except for the password // texbox) for each input textbox or is one span id fine how I currently have //it? Shouldn't I be able to display either message just using one span id?
if($(".newUsername").val().length < 6)
{
NewUsernameError.innerHTML= "The username must be at least 6 characters";
// NewUsernameError.innerHTML= "There is an already existing account with username";
}else
{
NewUsernameError2.innerHTML = '';
}
if($(".newPassword").val().length < 6) {
{
NewPasswordError.innerHTML= "The password must be at least 6 characters";
}else{
NewPasswordError.innerHTML = '';
}
if($(".newEmail")== "" && $(".newEmail") != /^[a-zA-Z0-9]#[a-zA-Z])+.[a-z])
{
NewEmailAddressError.innerHTML= "The email must not be left empty.";
NewEmailAddressError.innerHTML= "The email must contain # symbol in it.";
}else{
NewEmailAddressError.innerHTML= '';
}
if($(".repeatEmail").value != $(".newEmail").value && $(".repeatEmail") == ""){
NewRepeatEmailAddressError.innerHTML= "This repeat email doesn't equal to the first one entered.";
NewRepeatEmailAddressError.innerHTML= "This repeat email must not be blank.";
}else{
NewRepeatEmailAddressError.innerHTML= '';
}
.
Lots of problems here.
if($(".newEmail")== "" && $(".newEmail") != /^[a-zA-Z0-9]#[a-zA-Z])+.[a-z])
That tries to compare the <input> element instead of its contents.
if($(".repeatEmail").value != $(".newEmail").value && $(".repeatEmail") == ""){
That tries to compare undefined instead of the form element's contents. (jQuery doesn't use .value.)
Instead, you want .val():
if($(".newEmail").val() == "" && $(".newEmail").val() != /^[a-zA-Z0-9]#[a-zA-Z])+.[a-z])
...
if($(".repeatEmail").val() != $(".newEmail").val() && $(".repeatEmail").val() == ""){
A secondary problem is where you try to assign two error messages simultaneously:
NewRepeatEmailAddressError.innerHTML= "This repeat email doesn't equal to the first one entered.";
NewRepeatEmailAddressError.innerHTML= "This repeat email must not be blank.";
In these cases the second .innerHTML is going to immediately overwrite the first one, so the first error message will never be seen. Each of those errors needs to be in its own, separate if {} condition.
Third, this isn't how to do regex comparisons, that regex contains several syntax errors (no trailing slash, mismatched parens), and even if it worked it would disallow many valid email addresses:
$(".newEmail") != /^[a-zA-Z0-9]#[a-zA-Z])+.[a-z])
Better email address validation regexes can be found in e.g. this question, but even those can disallow some valid addresses. Keep things simple and test only for what the error message claims you're testing for, the presence of an # symbol:
/#/.test($('.newEmail').val())
Putting it all together
Cleaning your original function, converting all the vanilla js into jQuery (there's no real drawback to mixing them other than that it makes the code harder to read, but I figure if you've already got jQuery may as well use it), and rearranging some logic to simplify the code results in this:
var validate=function() {
// clear out the error display ahead of time:
var newUsernameError = $("#New_Username_error").html('');
var newPasswordError = $("#New_Password_error").html('');
var newEmailAddressError = $("#New_Email_error").html('');
var newRepeatEmailAddressError = $("#Repeat_Email_error").html('');
// just to make the later conditions easier to read, let's grab all the values into vars:
var newUsername = $('.newUsername').val();
var newPassword = $('.newPassword').val();
var newEmail = $('.newEmail').val();
var repeatEmail = $('.repeatEmail').val();
// presumably you'll want to prevent form submit if there are errors, so let's track that:
var errorsFound = false;
if (newUsername === "") {
errorsFound = true;
newUsernameError.html("The username must not be empty.");
} else if (newUsername.length < 6) {
errorsFound = true;
newUsernameError.html("The username must be at least 6 characters.");
}
if (newPassword.length < 6) {
errorsFound = true;
newPasswordError.html("The password must be at least 6 characters.");
}
if (newEmail === "") {
errorsFound = true;
newEmailAddressError.html("The email must not be left empty.");
} else if (!/#/.test(newEmail)) {
errorsFound = true;
newEmailAddressError.html("The email must contain an # symbol.");
}
if (repeatEmail !== newEmail) {
errorsFound = true;
newRepeatEmailAddressError.html("This repeat email doesn't equal to the first one entered.");
}
// No need to test for repeatEmail being empty, since that's already covered by the newEmail case above.
// OK, all conditions checked, now:
if (errorsFound) {
// prevent form submit. (If this is called in an onsubmit handler, just return false.)
} else {
// allow form submit.
}
console.log("Errors found: ", errorsFound);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
Username: <input class="newUsername">
<div id="New_Username_error"></div>
Password: <input class="newPassword">
<div id="New_Password_error"></div>
newEmail: <input class="newEmail">
<div id="New_Email_error"></div>
repeatEmail: <input class="repeatEmail">
<div id="Repeat_Email_error"></div>
</form>
<button onclick="validate()">Validate</button>
Keep one container for the errors you might expect to get on the input. I would do something like this to avoid all the else and else if's
$('#button2').on('click', function () {
// VALIDATE USERNAME
var newUserErrStr = '';
var newUsernameVal = $(".newUsername").val();
if(newUsernameVal.length < 6) newUserErrStr += "The username must be at least 6 characters";
document.getElementById("New_Username_error").innerHTML = newUserErrStr;
// VALIDATE PASSWORD
var newPasswordErrStr = '';
var newPasswordVal = $(".newPassword").val();
if(newPasswordVal.length < 6) newPasswordErrStr += "The password must be at least 6 characters";
document.getElementById("New_Password_error").innerHTML = newPasswordErrStr;
// VALIDATE EMAIL
var newEmailErrStr = '';
var newEmailVal = $(".newEmail").val();
if (newEmailVal === "") newEmailErrStr += "The email must not be left empty<br/>";
if (newEmailVal !== /^[a-zA-Z0-9]#[a-zA-Z])+.[a-z]/ ) newEmailErrStr += "The email must contain # symbol in it.";
document.getElementById("New_Email_error").innerHTML = newEmailErrStr;
});

Regex to replace non-numeric characters and insert dashes for phone number as it is typed

I need javascript to format a telephone number as it is typed. This would replace all non-numeric characters and insert dashes if the user doesn't type them in. So far this is the closest I've gotten, but it is thrown off if they put a dash in the wrong spot. The ideal solution would be to replace dashes only in the wrong spots. I was looking for a way to possibly replace the 4th and the 8th digit differently but haven't come up with a solution.
$('#TelephoneNo').keyup(function (ev) {
if (/[^0-9\-]/g.test(this.value))
{
this.value = this.value.replace(/[^0-9\-]/g, '');
}
if (/^(\d{3})(\d)/.test(this.value))
{
this.value = this.value.replace(/^(\d{3})(\d)/, '$1-$2');
}
if (/^(\d{3}-\d{3})(\d)/.test(this.value))
{
this.value = this.value.replace(/^(\d{3}-\d{3})(\d)/, '$1-$2');
}
});
Assuming you want the format "123-456-7890":
function formatPhoneNumber(s) {
var s2 = (""+s).replace(/\D/g, '');
var m = s2.match(/^(\d{3})(\d{3})(\d{4})$/);
return (!m) ? null : m[1] + " -" + m[2] + "-" + m[3];
}
<html>
<head>
<script type="text/javascript">
function CheckNum(ev) {
var inputval=document.getElementById("TelephoneNo").value;
debugger
if(inputval){
if (/[^0-9\-]/g.test(inputval))
{
inputval = inputval.replace(/[^0-9\-]/g, '');
}
if(detectPosition()){
if (/^(\d{3})(\d)/.test(inputval))
{
inputval = inputval.replace(/^(\d{3})(\d)/, '$1-$2');
}
if (/^(\d{3}-\d{3})(\d)/.test(inputval))
{
inputval = inputval.replace(/^(\d{3}-\d{3})(\d)/, '$1-$2');
}
}
document.getElementById("TelephoneNo").value=inputval;
}
}
function detectPosition() { var inputval=document.getElementById("TelephoneNo").value;
if(inputval.indexOf("-") ==4 || inputval.indexOf("-") ==8)
{
return 1;
}
return -1;
}
</script>
</head>
<body>
<input type="text" id="TelephoneNo" onkeyup="CheckNum(this)">
</body>
</html>
I know this is an old question, but I figured I might help someone out.
I did this xxx-xxx-xxxx as-you-type formatting using two cases: one for formatting where the length required one hyphen, and another for formatting with two required. That way, the last group always expects an unknown char count and doesn't wait until the end of the user input to enforce the format.
function formatPhone() {
var element = document.getElementById('phone');
var inputValue = element.value;
// length < 3 : no formatting necessary
if (inputValue.length > 3 && inputValue.length < 8)
// length < 8 : only one hyphen necessary, after first group of 3
// replace (remove) non-digits, then format groups 1 and 2
result = inputValue.replace(/\D/gi, '').replace(/(.{3})(.{0,3})/g, '$1-$2');
else
// length >= 8 : 2 hyphens required, after first two groups of 3
// replace (remove) non-digits, then format groups 1, 2, and 3
result = inputValue.replace(/\D/gi, '').replace(/(.{3})(.{3})(.{0,4})/g, '$1-$2-$3');
element.value = result;
}
Type a phone number, it will be formatted to xxx-xxx-xxxx as you type:<br/><br/>
<input type="text" id="phone" maxlength="12" onkeyup="formatPhone()"></input>

Regex: Check if string contains SSN in any part of the string

Can any one tell how to check if a String contains a social security number (SSN) using REGEX
Example data:
(1): my ssn is 123-44-8686
validate this ==> Need to return as true, since it contains a number in SSN format (XXX-XX-XXXX)
(2) my ssn is nothing ==> Need to return as false, since it does not contain a number in SSN format
No need to use REGEX.
Hopefully Something like this will work
var str = "123-44-8686";
var res = str.split("-");
if(res.length == 3){
var ssn1=res[0];
if(ssn1.length==3){
var ssn2=res[1];
if(ssn2.length==2){
var ssn3=res[2];
if(ssn3.length==4){
alert("valid formate");
}
}
}
}
else{
alert('Invalid formate');
}

Extract substring out of a user input phone number using Javascript

I am getting phone number input from user as +XXX-X-XXX-XXXX that (+XXX as country code), (X as city Code), (XXX as 1st 3 digits) and , (XXX as 2nd 4 digits). I used regular expression to confirm the entry as in following code;
function validate(form) {
var phone = form.phone.value;
var phoneRegex = /^(\+|00)\d{2,3}-\d{1,2}-\d{3}-\d{4}$/g;
//Checking 'phone' and its regular expressions
if(phone == "") {
inlineMsg('phone','<strong>Error</strong><br />You must enter phone number.',2);
return false;
}
if(!phone.match(phoneRegex)) {
inlineMsg('phone','<strong>Error</strong><br />Enter valid phone <br />+xxx-x-xxx-xxxx (or) <br />00xxx-x-xxx-xxxx.',2);
return false;
}
return true;
}
Its working very fine but the problem is that
EDIT : If the user inputs as +XXXXXXXXXXX (all together) and hit enter or go to another field, the input it self set according to the Regex that is +XXX-X-XXX-XXXX.
Can some one guide me with some example how to do this task.
Thank you
Set the element's onblur method a callback as follows:
var isValidPhoneNumber = function(string) {
...
}
var reformat = function(string) {
/*
* > reformat('example 123 1 1 2 3 123-45')
* "+123-1-123-1234"
*/
var numbers = string.match(/\d/g);
return '+' + [
numbers.slice(0,3).join(''),
numbers.slice(3,4).join(''),
numbers.slice(4,7).join(''),
numbers.slice(7,11).join('')
].join('-');
}
var reformatPhoneNumber = function() {
var inputElement = this;
var value = inputElement.value;
if (isValidPhoneNumber(value))
inputElement.value = reformat(inputElement.value);
else
// complain to user
}
Here are two example ways you could set the onblur callback handler:
document.getElementById('yourinputelement').onblur = reformatPhoneNumber;
<input ... onblur="reformatPhoneNumber"/>
You can augment reformatPhoneNumber with more validation code if you'd like, or just constantly validate the number as the user is typing it.
To only do this if your phone number is of the form +ABCDEFGHIJK, then add an string.match(/^\+\d{11}$/)!==null to your if statement. (^,$ mean the start and end of the string, \+ means a plus sign, and \d means a digit 0-9, repeated exactly {11} times). Specifically:
function isPlusAndEleventDigits(string) {
/*
* Returns whether string is exactly of the form '+00000000000'
* where 0 means any digit 0-9
*/
return string.match(/^\+\d{11}$/)!==null
}
Try shaping the input:
result = subject.replace(/^((\+|00)\d{2,3})-?(\d{1,2})-?(\d{3})-?(\d{4})$/mg, "$1-$3-$4-$5");
Then do next procedure.

Categories

Resources