JavaScript regexp? - javascript

This is the regexp:
$("#newpassword").keyup(function(e) {
var htm = "";
var pass = this.value;
var length = this.value.length;
if (pass) {
var score = 0;
if(length >= 8 && length <= 16) { //PASSWORD MIN/MAX NUMBER OF CHARACTERS
var upper = /[A-Z]/;
var lower = /[a-z]/;
var number = /^[0-9]+$/; //PATTERN FOR NUMBERS
var schar = /[!##$%^&*?_~+-=<>]/;
//LOOPS THROUGH PASSWORD TO CHECK FOR AT LEAST ONE OF EACH PATTERN
for (i = 0; i < length; i++) {
if (pass.substr(i, 1).match(upper)) {
var uletters = true;
score ++;
//AT LEAST ONE LETTER EXISTS
}
if(pass.substr(i,1).match(lower)) {
var lletters = true;
score++;
//AT LEAST ONE LETTER EXISTS
}
if(pass.substr(i,1).match(schar)) {
var schar = true;
score++;
}
if(pass.substr(i, 1).match(number)) {
var numbers = true;
var schar = false;
//AT LEAST ONE NUMBER EXISTS
score++;
}
}
}
}
});
The any two condition is true means password is ok, but the above code if(numbers == true && schar == true) user type only number display password ok.
Please help me what is the problem in my code.

You don't need to iterate over each character of your password, just do the following:
score += upper.test(password)?1:0;
score += lower.test(password)?1:0;
score += number.test(password)?1:0;
score += schar.test(password)?1:0;
(test returns true or false) and check the score afterwards.
In general it's recommendable not to be too restrictive about the users password. It seriously harms the user experience if they are told to how their password should look like. You can make it a recommendation though. (E.g. display a bar: weak (red) - strong (green) password. This is much more motivating than harassing the user with any error messages.) Let them pass on score 2 and higher.

You can probably use RegExp.test() or RegExp.exec() to "find" a regex match within your string, rather than iterating the characters yourself.
function validatePwd (pwd) {
if (pwd.length < 8)
return false;
if (pwd.length > 16)
return false;
var upperPatt = /[A-Z]/;
var lowerPatt = /[a-z]/;
var numberPatt = /[0-9]/; // FIXED -- this is a better pattern for numbers.
var scharPatt = /[!##$%^&*?_~+-=<>]/;
score = 0;
if (upperPatt.test( pwd))
score++;
if (lowerPatt.test( pwd))
score++;
if (numberPatt.test( pwd))
score++;
if (specialPatt.test( pwd))
score++;
// don't make it too hard for the poor user, please..
// -- they have to type all this horrible rubbish.
if (score < 3) {
return false;
}
// OK.
return true;
}

Related

To lower case using if else/ for

I am the very begginer (only if/else, for, while, slice etc) and i ve got a problem: so i wrote Hangman game. I need to put in there code saying ‘’let’s player upper case guess letter transform to lowercase one every time he puts uppercase letter”
Did i choose the right place for this new code in existing code?
Were my thoughts about appropriate code more or less right?
If not: what s wrong then?
var words = ["fish", "monkey", "pioni", "agreable"];
var randomWord = words[Math.floor(Math.random() * words.length)];
var answerArray = [];
for (var i = 0; i < randomWord.length; i++) {
answerArray[i] = "_";
}
var ramainingLetters = randomWord.length;
//Game circle
while (ramainingLetters > 0) {
alert(answerArray.join(" "));
var guess = prompt("Guess a letter or press cancel to exit game");
if (guess === null) {
break;
} else if (guess.length !== 1) {
alert("Enter only one letter");
} else if (guess == guess.toUpperCase()) {
guess = guess.toLowerCase();
} else {
//renew game cycle
for (var j = 0; j < randomWord.length; j++) {
if (randomWord[j] === guess) {
answerArray[j] = guess;
ramainingLetters--;
}
}
}
// stop game
}
alert(answerArray.join(" "));
alert(" Cool! this word was " + randomWord);
You could easily solve your problem by converting the chosen word to uppercase and everytime the user puts in a letter, make that uppercase too.
var randomWord = words[Math.floor(Math.random() * words.length)].toUpperCase();
And convert your quess always to uppercase
guess = guess.toUpperCase();
This way everything is consistent.
If they type in a letter in lowercase its getting converted to uppercase and compared with the word also in uppercase.

The output of my password generator is less than desired

I'm trying to make a password generator for a coding bootcamp but I'm running into an issue that has 2 outcomes both of which aren't desired. The HTML is very basic and I'm supposed to use prompts for the selection. I included my code but took out a few unnecessary things, the other 14 if-else statements, and a few variables. I'm turning in the project with the ugly formatting and spaces but still would like to know where I went wrong. The two outcomes are
The selections won't be unique and instead use the same character over and over
It comes out looking sloppy and adds spaces into it
function randomLower() {
return String.fromCharCode(Math.floor(Math.random() * 26) + 97);
}
//random uppercase from character code
function randomUpper() {
return String.fromCharCode(Math.floor(Math.random() * 26) + 65);
}
//random number from character code
function randomNumber() {
return String.fromCharCode(Math.floor(Math.random() * 10) + 48);
}
// random symbol from character code
function randomSymbol() {
let symbol = "!##$%^&*()_-><[]}{";
return symbol[Math.floor(Math.random() * symbol.length)];
}
// Get references to the #generate element
var generateBtn = document.querySelector("#generate");
// Write password to the #password input
function writePassword() {
var password = generatePassword();
var passwordText = document.querySelector("#password");
passwordText.value = password;
}
// Add event listener to generate button
generateBtn.addEventListener("click", writePassword);
// function for generatePassword
function generatePassword() {
//Confirms # of characters needed
click = parseInt(prompt("How many characters?", "8-128"));
if (!click) {
alert("Input is needed");
//Ensures the character count isn't too high or low
} else if (click < 8 || click > 128) {
click = parseInt(prompt("Answer must be between 8 and 128"));
} else {
//The procedding few lines will confirm other variables
useNumbers = confirm("Include numbers?");
useLower = confirm("Include lowercase letters?");
useUpper = confirm("Include uppercase letters?");
useSymbol = confirm("Include special characters?");
}
//If all prompts are denied
if (!useLower && !useUpper && !useNumbers && !useSymbol) {
choices = alert("At least one option is needed");
//If all prompts are accepted
} else if (useLower && useUpper && useNumbers && useSymbol) {
choices = randomLower().concat(randomUpper, randomNumber, randomSymbol);
//code only makes repeating characters
//choices = randomLower().concat(randomUpper(), randomNumber(), randomSymbol())
//placeholder for an array for user choices
var pWord = [];
//for loop to randomize selection
for (let i = 0; i < click; i++) {
var selected = choices[Math.floor(Math.random() * choices.length)];
pWord.push(selected);
}
//.join will take all choices in the array pWord and turns it into a string
var pass = pWord.join("");
UserInput(pass);
return pass;
}
// This puts the new password into the textbox
function UserInput(pass) {
document.getElementById("password").value = pass;
}
You only set choices if the user selects all the options.
When you set choices, you don't call the functions in the arguments to concat(). So you're concatenating the function definitions, not the random letters returned by the functions.
Even if you fix that to call the functions, you'll just get 4 characters. You need to call the randomXXX functions in the loop that generates each character.
In my code I've made choices an array of functions, not characters. I add each function to the array conditionally from the prompts. Then the loop picks a random function first, and calls it to get a random character of that type.
// function for generatePassword
function generatePassword() {
//Confirms # of characters needed
let click = parseInt(prompt("How many characters?", "8-128"));
let choices = [];
if (!click) {
alert("Input is needed");
//Ensures the character count isn't too high or low
} else if (click < 8 || click > 128) {
click = parseInt(prompt("Answer must be between 8 and 128"));
} else {
//The procedding few lines will confirm other variables
if (confirm("Include numbers?")) {
choices.push(randomNumber);
}
if (confirm("Include lowercase letters?")) {
choices.push(randomLower);
}
if (confirm("Include uppercase letters?")) {
choices.push(randomUpper);
}
if (confirm("Include special characters?")) {
choices.push(randomSymbol);
}
}
//If all prompts are denied
if (choices.length == 0) {
alert("At least one option is needed");
return;
}
//placeholder for an array for user choices
var pWord = [];
//for loop to randomize selection
for (let i = 0; i < click; i++) {
let selected = choices[Math.floor(Math.random() * choices.length)];
pWord.push(selected());
}
//.join will take all choices in the array pWord and turns it into a string
var pass = pWord.join("");
return pass;
}
console.log(generatePassword());
function randomLower() {
return String.fromCharCode(Math.floor(Math.random() * 26) + 97);
}
//random uppercase from character code
function randomUpper() {
return String.fromCharCode(Math.floor(Math.random() * 26) + 65);
}
//random number from character code
function randomNumber() {
return String.fromCharCode(Math.floor(Math.random() * 10) + 48);
}
// random symbol from character code
function randomSymbol() {
let symbol = "!##$%^&*()_-><[]}{";
return symbol[Math.floor(Math.random() * symbol.length)];
}
Im writing the same pattren as per passwords generators website. you can add this javascript in your html. You can generate random alphanumeric strings in JavaScript using the following code:
function generateRandomString(length) {
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
var string_length = length || 8;
var randomstring = '';
for (var i=0; i<string_length; i++) {
var rnum = Math.floor(Math.random() * chars.length);
randomstring += chars.substring(rnum,rnum+1);
}
return randomstring;
}

How to check if the user's first and last names are in the password?

I'm validating a password following these criteria:
1•Letters and Numbers
2•Allow ‘!’, ‘?’, ‘.’
3•Min 1 capital letter
4•Min 8 chars
5•Max 16 chars
6•Min 2 numbers
7•Does not contain first name
8•Does not contain last name
This code works well for the first 6 conditions, still not able to validate 7 and 8.
function validatePassword(){
var inputs = document.getElementsByTagName('input');
var allowedInput = new RegExp("^(?=(.*\\d){2})(?=.*[A-Z])[a-
zA-Z0-9!?.]{8,16}$");
for(i = 0; i < inputs.length; i++){
if(inputs[i].type == "password"){
if(inputs[i].value.match(allowedInput)){
console.log("Pass Good");
}
else{
console.log("Only numbers, letters!,?,. allowed\n" +
"Between 8 - 16 chars\n" +
"Minimum one uppercase letter\n" +
"Minimum 2 digits\n");
}
}
}
}
Since you did not tag with regex here is another way:
var fnlc = firstname.toLowerCase();
var lnlc = lastname.toLowerCase();
var vallc = inputs[i].value.toLowerCase();
var hasname = (vallc.indexOf(fnlc) >= 0 || vallc.indexOf(fnlc) >= 0);
If you have your heart set on a regex because you love it so much ;), then just test the names separately:
var testNames = new RegExp(firstname+'|'+lastname, "gi");
var hasname = testNames.test(inputs[i].value); // true if found
Here is the javascript code to validate the first name and last name with regular Expression using Javascript
test() – This function is used to perform a regular expression match in JavaScript.
var regName = /^[a-zA-Z]+ [a-zA-Z]+$/;
var name = document.getElementById('nameInput').value;
if(!regName.test(name)){
alert('Invalid name given.');
}else{
alert('Valid name given.');
}
<script>
function validate(){
var regName = /^[a-zA-Z]+ [a-zA-Z]+$/;
var name = document.getElementById('name').value;
if(!regName.test(name)){
alert('Please enter your full name (first & last name).');
document.getElementById('name').focus();
return false;
}else{
alert('Valid name given.');
return true;
}
}
</script>
For valdation 7 and 8, you can use the Array.prototype.includes() and modify your code as shown below:
I'm assuming firstName and the lastName to be the variables you can get it from DOM using one of the Document.querySelector() or any other DOM manipulator.
function validatePassword(){
var inputs = document.getElementsByTagName('input');
var allowedInput = new RegExp("^(?=(.*\\d){2})(?=.*[A-Z])[a-
zA-Z0-9!?.]{8,16}$");
for(i = 0; i < inputs.length; i++){
if(inputs[i].type == "password" && inputs[i].includes(firstName) && inputs[i].includes(lastName)){
if(inputs[i].value.match(allowedInput) && ){
console.log("Pass Good");
}
else{
console.log("Only numbers, letters!,?,. allowed\n" +
"Between 8 - 16 chars\n" +
"Minimum one uppercase letter\n" +
"Minimum 2 digits\n");
}
}
}
}

Javascript Averaging Calculator(Multiple Values entered by the user)

I want to be able to have a user enter multiple grades and then have the Javascript to average those grades that are entered. When the user is done entering grades, they can click cancel and close the Propmt Box, and if they don't enter any grades at all (defaults at 0), then the program displays that there were no grades entered.
I'm pretty new at this! I'm taking a javascript course at my College, and it's a bit confusing because the teacher doesn't teach! All we have to reference to is W3schools, which this stuff isn't listed at all!
Here's another explanation:
"Develop a program to allow a teacher to enter an arbitrary number of grades, perform an average calculation and then display the result in a grammatical sentence. The program must also tell the user if no grades were entered. You are required to use a loop and an “if else” statement. Be sure to declare all variables and test for the possibility of division by zero."
<script type = "text/javascript">
var gradeCounter = 0,
gradeValue = 0,
total = 0,
average, grade;
var sum = 0;
var i = 0;
while (gradeValue != -1 && gradeValue <= 100) {
//Prompt the user
grade = prompt("Enter Grades, -1 to Quit:", "0");
//Parse the prompt result to a int
sum += parseInt(grade);
i++;
if (i >= 0 && grade != null) {
document.getElementById("average").innerHTML = "The average of the grades you've entered are " + sum / i + ".";
} else {
document.getElementById("error").innerHTML = "There were no grades entered";
}
} </script>
Thanks again!
this does ok
updated
updated again
JSFIDDLE
// note: the dom must be ready before execution
var btn = document.querySelector('button'),
res = document.getElementById('average');
btn.addEventListener('click', function(e) {
var val = prompt('Enter comma delimited grades to average');
val = val.length ? val.replace(/\s/g, '').split(',') : '';
var count = val.length || 0; // no 0 division
if (!count) {
res.innerHTML = 'you must enter comma delimited numbers to average';
return;
} else {
var average = val.reduce(function(a, b) { // is a loop
return +a + +b;
});
res.innerHTML = (average /= count).toFixed(1);
}
});
html
<button id="avgBtn">Prompt</button>
<p>Average: <span id="average"></span></p>
var grades = [];
// initialize the array that will store the entries
var sum = 0;
// initialize the variable that will add the array values together
var average;
// initialize the variable that will contain the final result
var invalid = [];
// initialize the variable that will be used to make sure the user inserts something
for (i = 0; i < 5; i++) {
// repeat the following code 5 times
grades[i] = prompt("Please enter a grade. (You will be asked for 5 grades)", "");
// ask the user for a grade and store it to the array
}
for (i = 0; i < grades.length; i++) {
if (grades[i] === "" || grades[i] === null) {
invalid[invalid.length] = grades[i];
}
}
if (invalid.length !== 5) {
for (i = 0; i < grades.length; i++) {
// repeat this code the same amount of times as there are entries in the array (5)
sum += Number(grades[i]);
// add the entries together. make sure they are numbers using the Number() function
}
var average = sum / grades.length;
// divide the added entries by the number of entries (again, 5)
alert("The average of all of your numbers is: " + average);
// alert the user of the completed average
} else {
alert('You need to enter grades for this to work! Please reload the page to try again.');
}

Javascript in list

What's the easiest way to check to see if a number is in a comma delimited list?
console.log(provider[cardType]);
//returns: Object { name="visa", validLength="16,13", prefixRegExp=}
if (ccLength == 0 || (cardType > 0 && ccLength < provider[cardType].validLength)) {
triggerNotification('x', 'Your credit card number isn\'t long enough');
return false;
} else {
if ($('.credit-card input[name="cc_cvv"]').val().length < 3) {
triggerNotification('x', 'You must provide a CCV');
return false;
}
Seems similar to this SO question.
Just .split() the CSV and use inArray.
Not sure how your sample code relates to checking to see if a number is in a comma delimited list...
Also not sure if this is the easiest way, but it's what springs to mind:
<script type="text/javascript">
var myNumbers = "1,2,3,4,5";
var myArray = myNumbers.split( ',' );
// looking for "4"
for ( var i=0; i<myArray.length; i++ ) {
if (myArray[i] == 4) {
alert('Found it!');
break;
}
}
I do not see where you have a significant comma delimited list in the script you posted.
The fastest way could be something like
var csvList ="a,b,c,d,e,f,g,h";
var testList = ","+csvList+",";
var needle = "f";
alert(testList.indexOf(","+needle+",")!=-1)
just to be different ;)
If it's just a list of comma separated numbers with nothing fancy, you can just use the split method:
var numbers = list.split(",");
This will give you an array of all of the numbers in the list. Checking whether a number is in an array is trivial.
Native JavaScript and therefore cross-browser compliant. Some frameworks provide functions that do this for you, but you don't get more basic than the following.
var numbers = list.split(",");
var count = numbers.length;
var exists = false;
for (var i = 0; i < count; ++i) {
if (numbers[i] == anumber) {
exists = true;
break;
}
}
From your sample, I assume your question was "How do I see if a number is within a range of two values specified by a single-comma-delimited string?":
function inRange( number, stringRange ){
var minmax = stringRange.split(',');
minmax[0] = minmax[0]*1; //convert to number
minmax[1] = minmax[1]*1; //convert to number
minmax.sort(); // Ensure [0] is the min
return number>=minmax[0] && number<=minmax[1];
}
Try this one...
console.log(provider[cardType]); //returns: Object { name="visa", validLength="16,13", prefixRegExp=}
var regExp = new RegExp(",?" + ccLength + ",?");
if (ccLength == 0 || (cardType > 0 && !regExp.test(provider[cardType].validLength)))
{
triggerNotification('x', 'Your credit card number isn\'t long enough');
return false;
}
else
{
if ($('.credit-card input[name="cc_cvv"]').val().length < 3)
{
triggerNotification('x', 'You must provide a CCV');
return false;
}
}

Categories