IF/ else statements and Operators - javascript

I working on a form but I have some troubles with the last if statement ( it's not working.
count is global and start as 0, for each field with the correct character filled in this will happen: count = count+1;
but if I clicked submit and leave 2 fields with not the correct character
( that should be count = 6 ) it doesn't give me an alert but skips it
this is how it should be.
check if password equals confirm_password
check if fields or not empty
check if fields have the correct characters ( count start as count = 0 , foreach field that is correct it it goes count = count +1,
in totaal it can get 8 but at 6 it still keeps submitting).
function validateForm() {
var fields = ["voornaam", "achternaam", "Email", "Wachtwoord", "Herhaal_Wachtwoord", "Straatnaam", "Huisnummer", "Postcode", "Woonplaats", "Telefoonummer"];
if (pass1.value !== pass2.value) {
alert("Wachtwoord komen niet overeen");
return false;
}
var l = fields.length;
var fieldname;
for (i = 0; i < l; i++) {
fieldname = fields[i];
if (document.forms["register"][fieldname].value === "") {
alert(fieldname + " can not be empty");
return false;
}
}
if (count < 8) {
alert("iets is niet goed ingevuld");
return false;
}
}

You have returned the false boolean before you have given the alert prompt! Just change the last if statement like this:
if (count < 8) {
alert("iets is niet goed ingevuld");
return false;
}

Related

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");
}
}
}
}

multiple comma seperate value compare using JS

I want validation using a comma separated value.
Here in the image, there are two fields : one is "Saloon Price" (value : 10,10,10,10), and another is "Saloon Offer Price" (value : 11,11,11,11).
The first value must be lower than the second.
Saloon price Value >= Saloon Offer Price value
validations based on first value of saloon price and saloon offer price same for second , 3rd ...n
var size_weight_lengh = size_weight.split(',');
var saloon_price = validator.getFieldElements('saloon_price').val(),
saloon_price_lengh = saloon_price.split(',');
var saloon_offer = validator.getFieldElements('saloon_offer_price').val(),
saloon_offer_lengh = saloon_offer.split(',');
if(saloon_price_lengh.length === saloon_offer_lengh.length) {
for(var i=0; i<= saloon_price_lengh.length-1; i++) {
if((saloon_price_lengh[i]) >= (saloon_offer_lengh[i])) {
return true;
}
return false;
}
}
Split the string and then do a value comparison of two array elements.
It uses "break" and "continue" to reduce the unnecessary iterations over the loop.
Here is the full script. Adjust the functionality accordingly.
$(document).ready(function () {
var value = ComparePrice();
alert(value);
});
function ComparePrice() {
var salonOfferPrice = $('#saloon_offer_price').val();
var salonPrice = $('#saloon_price').val();
var offerPriceArray = salonOfferPrice.split(",");
var priceArray = salonPrice.split(",");
var isValid = false;
if (offerPriceArray.length == priceArray.length) {
for (var i = 0; i < offerPriceArray.length; i++) {
for (var j = 0; j < priceArray.length; j++) {
if (i == j) {
if (offerPriceArray[i] < priceArray[j]) {
alert(offerPriceArray[i] + "is less than" + priceArray[j]);
isValid = true;
}
else {
alert(offerPriceArray[i] + "is greater than or equal" + priceArray[j]);
return false;
}
}
else {
continue;
}
}
}
}
return isValid;
}
You have to do value by value comparison.
var sp="10,20,30"; //get your field values here
var sop="5,10,15";
var spArr = sp.split(','); //split the values using comma
var sopArr = sop.split(',');
if(spArr.length === sopArr.length){
for(var i in spArr){
if(parseInt(spArr[i])<parseInt(sopArr[i])){
//throw some error or your logic goes here.
}
}
}
Just make sure that you accept only numbers and comma using some regex check in the text field.

javascript Letters only

I have created a quiz on javascript that once the user answers 4/6 or more correct they will then be asked for a First Name, Last Name and then be given a random 4 digit code. The part I'm having trouble with is making the FirstName and LastName letters only and also not allow and empty prompt.
Anyone know how i'd implement a Regex into this?
Anyone able to help?
function getAnswers(){
var amountCorrect = 0;
for(var i = 1; i <= 10; i++) {
var radios = document.getElementsByName('q'+i);
for(var j = 0; j < radios.length; j++){
var radio = radios[j];
if(radio.value == "1" && radio.checked) {
amountCorrect++;
}
}
}
alert("Correct number of answers: " + amountCorrect + " / 6");
if (amountCorrect <= 3){
alert("You have not passed on this occasion. You will now be taken back to the homepage.");
window.history.go(-1); // Go back a step
}
else{
var firstname = prompt("Please enter your first name.");
var lastname = prompt("Please enter your last name.");
alert("Your login Code for the store is: " + firstname.substring(1, 0) + lastname.substring(1, 0) + (generateCode())); // Do the generateCode function
close();
}
}
try this..
var alphaExp = /^[a-zA-Z]+ [a-zA-Z]+$/;
var firstname =prompt("Please enter your first name And Last Name","");
if (firstname ==null || firstname =="")
{
alert("First and last name must be filled out!");
location.reload(true);
}
else if (!firstname.matches(alphaExp))
{
alert("Name must contain letters only!")
location.reload(true);
}
else{ // your code here.
}
Try this regex:
^[A-Z][a-zA-Z]*$
This regex matches a string of letters:
Starting with the letter A-Z
Only allow letters from a-z and A-Z
It will not match an empty line or any other character.
/^[a-zA-Z]+$/
this will work for u.

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 regexp?

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;
}

Categories