im having some issues concerning my javascript code for password. here's my code .that part is working fine, but i want to put another condition where my password should contains at least 8 characters and must abide the following rules : no spaces, contains at least 1 Uppercase and a number. concerning the mobile, it must always start with the no. 5 . help <3
function formValidation() {
var mobile = document.forms["form"]["mobile"].value;
var password = document.forms["form"]["password"].value;
//reg expression check
var checkNumbers = /^[0-9 ]+$/;
$(document.forms["form"]["mobile"]).focus(function(){
$(document.forms["form"]["mobile"]).css("background-color", "white");
});
$(document.forms["form"]["password"]).focus(function(){
$(document.forms["form"]["password"]).css("background-color", "white");
function clear(){
$(document.forms["form"]["mobile"]).focus(function(){
$(document.forms["form"]["mobile"]).css("background-color", "white");
});
$(document.forms["form"]["password"]).focus(function(){
$(document.forms["form"]["password"]).css("background-color", "white");
});
}
if (mobile == null || mobile == "") {
error[error.length]=("Enter your mobile number");
document.form.mobile.focus();
$(document.forms["form"]["mobile"]).css("background-color", "blue");
;
}else if (mobile != null || mobile != "") {
if(!checkNumbers.test(mobile)){
error[error.length]=("Enter Only numeric Characters for mobile phone");
document.form.mobile.focus();
$(document.forms["form"]["mobile"]).css("background-color", "blue");
}
}
if (password == null || password == "") {
error[error.length]=("Enter a password");
document.form.password.focus();
$(document.forms["form"]["password"]).css("background-color", "blue");
}
}
<form name="form" onsubmit="return formValidation()" action="process.html">
Mobile phone:
<input type="text" name="mobile" id="mobile"></br></br>
Password:
<input type="password" name="password" id="password"></br></br>
</form>
<input id="submit" type="submit" name="submit" id="submit">
If you break it down into parts you can do this really easily and inform the user exactly which constraint they are failing, like this:
// Check the length:
if (password.length < 8) { // ... not long enough }
// Check if it has at least one upper case:
if (password.match(/[A-Z]+/g) === null) { // ... no upper case characters }
// Check if it has at least one number:
if (password.match(/\d/g) === null) { // ... no numbers }
// Password passes validation!
Test if all your conditions are met (c1 condition 1 and so on)
var c1 = (password.toLowerCase() != password);// if it HAS uppercase letters, it won't match
var c2 = password.length > 8;
var c3 = !(password.indexOf(" ") > -1); // no spaces
var c4 = password.match(/\d+/g); // matches numbers
You can create a RegExp object and then pass in your password to its test method. The RegExp object can use positive lookaheads to assert that it finds an uppercase character and a digit character.
Finally, you can test that the password is at least 8 characters long and contains no white-space characters by attempting to pattern match at least 8 non-whitespace characters between the beginning-of-string token (^) and the end-of-string token ($). The pattern match will consume the entire string so if any whitespace characters are found, the test will fail, and if there are less than 8 characters, the test will also fail.
/(?=.*[A-Z])(?=.*\d)^\S{8,}$/.test(password)
^uppercase ^digit ^8+ characters in length and no whitespace
This expression will evaluate to true if the password is okay and false if not.
Related
I'm trying to solve a password checker challenge and I've got to a stage where 1 string is matching for two expressions.
Rules:
return 'too short' for any string that is less than 6 characters
return 'okay' if the string is less than 12 characters, features one or more underscores, or a number, or with a mix of uppercase/lowercase letters
var str = 'aBB33'
var lessthansixRegex = new RegExp(/^(?=.*?[a-z])(?=.*?[A-Z])|(?=.*?\d{1}){0,6}$/);
var okayRegex = new RegExp(/(?=.*?[a-z])(?=.*?[A-Z])|(?=.*?\d{1})|(?=.*?[_]{1})/);
if (okayRegex.test(str) && str.length < 12) {
return 'okay';
} else if (tooshortRegex.test(str) && str.length < 6) {
return 'too short';
}
Is there a way to check this or are the paramaters of the challenge messed up.
One solution you might easily spot is the lack of '' however the 'okay' regex must have that parameter as an or '|' because there are other strings than need to match it that also don't include ''.
Feel free to let me know if you spot any other bugs.
Thanks a lot!
I think you've overcomplicated things here, why not just check the string lengths rather than write a regex for it? Also I think your regex could be simpler:
var str = 'aBB33';
var okayRegex = /[_\d]|[A-Z]+.*[a-z]+|[a-z]+.*[A-Z]+/;
if (str.length < 6 || str.length > 11) {
return 'password must be between 6 & 11 characters';
} else if (okayRegex.test(str)) {
return 'ok';
} else {
return 'invalid password';
}
Seeing as this is about the regex let me explain what's happening:
[_\d] // match any underscore or digit (number)
| // or (checks whether what's before or after is true)
[A-Z]+.*[a-z]+ // check for at least one A-Z followed by any gap
// of characters followed by at least one a-z
| // or
[a-z]+.*[A-Z]+ // reverse of last check (lower then upper)
Hope that helps!
Your regex seems too complicated. You can reach your solution by testing against each individual regex and provide a specific error message based on each condition by doing something like this
var containsNumber = new RegExp('\d');
var containsUnderscore = new RegExp('[_]');
var containsUpperCase = new RegExp('[A-Z]');
var containslowerCase = new RegExp('[a-z]');
if (str.length < 6 || str.length > 11) {
return 'password must be between 6 & 11 characters';
} else if (!containsNumber.test(str)) {
return 'password must contain a number';
}else if (!containsUnderscore.test(str)) {
return 'password must contain underscore';
}else if (!containsUpperCase.test(str)) {
return 'password must contain upper case character';
}else if (!containslowerCase.test(str)) {
return 'password must contain lower case character';
}
Trying to validate my form and set up a variable for invalid characters, but I'm having trouble getting them recognized because they're just a bunch of symbols? -
function validation(){
var Name =
document.getElementById("name").value;
var Email = document.getElementByID("email").value;
var invalidSymbol = /[\~\`\!\#\$\%\^\&\*\(\)\-\+\{\}\:\\\;\"\'\<\>\?\,\]/;
if Name == ""{
alert("Please enter your name");
document.getElementById("Name").focus();
return false;
}else if (Email == "" | | Email.indexOf("#")<1 || Email.lastIndexOf("#")+2 || Email.lastIndexOf(".")+2>=Email.indexOf("#").length || Email.match(invalidSymbol)){
alert ("Please enter a valid e-mail address");
document.getElementById("email").focus();
return false;
}else{
return true;
}
}
var desired = stringToReplace.replace(/[^\w\s]/gi, '')
As was mentioned in the comments it's easier to do this as a whitelist
- replace the characters which aren't in your safelist.
The caret (^) character is the negation of the set [...], gi say
global and case-insensitive (the latter is a bit redundant but I
wanted to mention it) and the safelist in this example is digits, word
characters, underscores (\w) and whitespace (\s).
As stated here:
javascript regexp remove all special characters
by
annakata
I'm trying to implement password validation using regex or javascript.
unfortunately i'm a total newbie to Regex :/
the criteria are :
minimum length: 8 characters (can be upper or lower case)
must contain 1 special character (something like !?$%&#)
must contain at least one number
i found the following snippet but it's missing checking for at least character of type special+number ..
function validPassword(password) {
var has_letters = (/[a-zA-Z]/).test(password);
var has_numbers = (/[0-9]/).test(password);
var has_length = 3 <= password.length && password.length <= 30;
return has_letters && has_numbers && has_length;
}
thanks
You can use below regex to validate your password:
var regex = "^(?=.*[A-Za-z])(?=.*\d)(?=.*[$#$!%*#?&])[A-Za-z\d$#$!%*#?&]{8,}$";
This will check validation for Minimum 8 characters at least 1 Alphabet, 1 Number and 1 Special Character.
Another way would be
function validPassword(password) {
return password.length > 8
&& password.match( /[\d]/ )
&& password.split( /[\W]/ ).length == 2 ;
}
password.length > 8 checks the length should be minimum 8
password.match( /[\d]/ ) checks if it has at least one number
password.split( /[\W]/ ).length == 2 checks if it has one special character
Your regex should be like this:
(?=^.{8,}$)(?=.*[0-9])(?=.*[A-Z])(?=.*[a-z])(?=.*[^A-Za-z0-9]).*
Here is the detail:
(?=^.{6,}$) - String is > 5 chars
(?=.*[0-9]) - Contains a digit
(?=.*[A-Z]) - Contains an uppercase letter
(?=.*[a-z]) - Contains a lowercase letter
(?=.*[^A-Za-z0-9]) - A character not being alphanumeric.
Add one extra check:
function validPassword(password) {
var has_letters = /[a-zA-Z]/.test(password);
var has_numbers = /\d/.test(password);
var has_special = /[!?$%&#]/.test(password);
var has_length = (password.length >=8 && password.length <= 30);
return has_letters && has_numbers && has_special && has_length;
}
However if you want a single regex to do all this then use lookaheads:
var re = /^(?=.*\d)(?=.*[!?$%&#])(?=.*?[a-zA-Z]).{8,30}$/;
var isValid = re.test(password);
I was creating a regular expression in angular to validate password which should have
A number
A uppercase letter
A lowercase letter
Only few symbols i.e !##$%
position of any character or symbol is not restricted.
I have tried this regex
/(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z])/
But the above regex takes any special character to be valid... I just want !##$% this to be valid ele invalid
I'm not sure that all the things you want to do are possible in single regex. But you can use a simple validation function that uses some regex's:
function validate (pass) {
if (
/[A-Z]/.test(pass) && // uppercase letter is required
/[a-z]/.test(pass) && // lowercase letter is required
/[0-9]/.test(pass) && // number is required
/[!##$%]/.test(pass) && // predefined symbol is required
!/[^A-Za-z0-9!##$%]/.test(pass) // there is nothing unwanted
) {
return true;
}
return false;
}
Here is jsfiddle to show that it works.
Try a ng-change listener - something like the following HTML:
<input ng-model="pw" ng-change="checkPwPolicy(pw)">
<div ng-hide="passwordPolicyValid">Your password is too weak!</div>
Combined with this Javascript inside the scope of the controller of this form:
function checkPwPolicy(password) {
var valid = true;
// at least 1 number
valid = valid && password.match(/[0-9]/).length > 0;
// at least 1 uppercase
valid = valid && password.match(/[A-Z]/).length > 0;
// ...
$scope.passwordPolicyValid = valid;
}
Some things you could do to improve this implementation are that you could make the change listener fire less often, hide the error message when the password has not been touched, as well as adding more detailed errors to the password policy message.
I am using a regex to validate an email address in JavaScript.
The regex is pretty simple. It checks three things: 1)'#' , 2)'.' ('dot' as in something#gmail.com), and 3) 'a-z' in an email address. If all three return true, email address is valid (according to my validation, atleast)
Here is the code:
function checkemail(){
var e = document.getElementById("email").value;
if((e.match(/#/g)==null)||(e.match(/[a-z]/ig)==null)||(e.match(/./g)==null)){
//display error message
}
}
My question is:
(e.match(/./g)==null); //returns false even though there are no dots in the string e
returns false even when there are no dots in string.
For example:
("thisIsMyEmail".match(/./ig))==null //returns false
Why does it return false when it should be true?
/./g (or /./ig) will match any string that as at least one character in it. . is special in regular expressions, it means "any character here."
For an actual dot, escape it with a backslash: /\./g.
First off, you don't need to check if the string is null. Simply use this:
var email = "Godisgood#gmail.com";
if (email.match(/^\S+\#\S+\.\S+$/i)){
alert("Email address passed validation.");
}
you have to escape the .
The unescaped period means matches any character.
Meaning having a string "abc" using your expression would result in an array containing the characters 'a', 'b', and 'c'.
In your snippet the correct answer is
(e.match(/\./g)==null);
This should result to what you're expecting
Try this
(e.match(/\./g)==null);
. matches any character so needs escaping /\./g
I know you have already got the answer.
But I just want to give an advice.
My advice is - don't use the javascript code to validate any email address; because as per your code, #domain., #domain.com these all are also valid email, but everybody knows these are not a valid email address.
So use the below code:
let email = $(this).val();
var positionOfAt = email.indexOf("#");
var positionOfDot = email.lastIndexOf(".");
if(email.search("#") == -1 || //if '#' is not present
email.search(" ") >= 1 || //if blank space is present
email.search(".") == -1 || //if "." is not present
positionOfAt < 1 || //if there is no character before "#", at least one character should be present before "#"
positionOfDot - positionOfAt <= 2 || //between '#' and '.', if there is not at least two character
email.length - positionOfDot <= 2) //if after '.' there is not at least two character)
{
console.log("Invalid email id")
}
else
{
console.log("Valid email id")
}