Javascript user must enter 6-character code - javascript

So, I need the user to enter a 6-character registration number. The prompt, should repeat if the user does not enter a 6-character code or presses cancel. For context, The prompts ask the user more about their vehicle and 5 other vehicles, and then displays the information in a table.
vehicle.registration = prompt("Please enter a 6-character vehicle registration number");
if (value.length <6) {
vehicle.registration = prompt("That is not a valid response. Please enter a 6-character registration number");
continue;
else {
document.getElementById("registration" + i).innerHTML = vehicle.registration;
}
I've tried Value.length, string.length.. I'm not sure why it isn't working.

You need to access or store the value of the prompt window i.e. vehicle.registration.
Also, you can place the validation logic in a while-loop to ask until valid input is received.
See: https://developer.mozilla.org/en-US/docs/Web/API/Window/prompt
const promptMessage = 'Please enter a 6-character vehicle registration number',
maxRegistrationLength = 6;
let vehicle = {}; // Reference scope
// The initial request
vehicle.registration = prompt(promptMessage);
// Keep validating until true
while (vehicle.registration.length < maxRegistrationLength) {
// Ask again...
vehicle.registration = prompt('That is not a valid response. ' + promptMessage);
}
// Display the valid input
document.getElementById('registration').innerHTML = vehicle.registration;
<p>Registration #<span id="registration"></span></p>

Related

Do While Loop Mixed With Function Loop

I am writing a simple program for school and running into trouble with an issue I am hoping someone could help me with
These are the assignment parameters:
Create a small JavaScript program that:
Creates a variable 'total' with a value of 0.
Use a do-while loop & function to prompt the user to enter a series of numbers, or the word "quit" - the quit command should be case insensitive.
If the user enters a number, add the new number to a running total.
If the user enters the word "quit" the loop should stop execution.
If the user enters a word other than quit the prompt message should change to let the user know they entered an invalid data type
When the loop is exited, display a message giving the total of the numbers entered
My code achieves all assignment parameters except I can't figure out how to get the prompt to disappear after the quit command is entered. The result still displays on the screen but the prompt keeps looping.
Here is my code:
var inputCounter = 0;
var total = 0;
newInput = null;
quit = /quit/i
function askForNum(a) {
do {
var newInput = prompt(a);
if (!newInput.match(quit)) {
if (newInput < "A" && newInput > "" ) {
var addThis = parseFloat(newInput);
}
if (isNaN(newInput)) {
askForNum("That wasn't a number! type \"quit\" to see the results!");
} else {
total += addThis;
inputCounter++;
askForNum("Every number you enter gets added together! type \"quit\" to see the results!");
}
}
} while (!newInput.match(quit)) {
document.getElementById("addition-script").innerHTML = "<b>TOTAL:</b> " + total + "<br><b># OF ENTRIES:</b> " + inputCounter;
return;
}
}
if (total == 0){
askForNum("initial: Every number you enter gets added together! type \"quit\" to see the results!");
}
You are calling the askForNum function from inside itself (recursion), in effect starting a new do-while loop inside the previous one every time you type anything other than "quit".

Why doesn't this if/else run before the other prompts

var password = prompt('Please enter your password.');
if (password!=="cat" && password!=="cow") {
console.log(password);
location.assign("http://www.google.com")
}
//The rest of prompts
var age = prompt("What is your age?");
var name = prompt('What is your name?');
var homeTown = prompt('Where are you from?');
var favoritDog = prompt("What's your favorite dog?");
So that's my code, (I'm a beginner and just messing around with concepts), if the incorrect password is put in, shouldn't it redirect me to google right away? Because when I run that code, it gives me all the prompts first before the redirect. Any help is appreciated, thank you.
Because doing location.assign will not stop the execution of JavaScript, it will keep going. It will do the location assignment after the sequential JavaScript finishes. Since prompt blocks the current execution, for it to finish it will need to go through the prompts. To prevent it simply add your prompts to an else:
var password = prompt('Please enter your password.');
if (password!=="cat" && password!=="cow") {
console.log(password);
location.assign("http://www.google.com")
} else {
//The rest of prompts
var age = prompt("What is your age?");
var name = prompt('What is your name?');
var homeTown = prompt('Where are you from?');
var favoritDog = prompt("What's your favorite dog?");
}

how to validate either email or mobile in same input field?

I have coded not empty on fields. how do i check that email is valid or either mobile number is valid one that too us phone number.
if(mob_or_email==""){
document.getElementById('busp_email').innerHTML="Mobile/Email required";
$("#busp_email").removeClass('field_validation_error hidden');
$("#busp_email").addClass('field_validation_error');
$("#busi_name").css("color","#f42156");
}
if($('#login_password').val()==""){
document.getElementById('logp_pwd').innerHTML="Password required";
$("#logp_pwd").removeClass('field_validation_error hidden');
$("#logp_pwd").addClass('field_validation_error');
$("#log_pwd").css("color","#f42156");
}
If I understand your request correctly, you may have an e-mail or a phone number in the same field?
You will need regular expressions for this (If my suggestions are not satisfying, search trough the internet, there are many samples for specific cases)
function validateEmail(email) {
var re = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
return re.test(email);
}
function validatePhone(phone) {
var re = /^(\([0-9]{3}\) |[0-9]{3}-)[0-9]{3}-[0-9]{4}$/;
return re.test(phone);
}
With these functions you can validate e-mail and us phone numbers.
just use
if (validateEmail(mob_or_email) or validatePhone(mob_or_email)) {
//is either a valid email or (us) phone number
}

Javascript Functions with loops assignment

I found a similar question for this same assignment but that person was using a different type of loops. I have been struggling with this assignment and even with the teacher giving me pseudo code to try to explain it further I am still having difficulties with it writing out what it's supposed to in the end.
We are supposed to create an array that holds the price of theater tickets, then make a html table that has the different level of tickets and prices that correspond with the numbers in the array. After this we prompt the user for their name and validate that they did enter something. Then we are supposed to create a function named numSeats that prompts the user for the number of
seats that they want to buy and validate that they entered a number and the maximum number of seats they can buy in one transaction is 6.
We are supposed to use a loop to
prompt the user until they enter a valid number, then create a function named seatingChoice that prompts the user for where they would like the seats to be by indicating the correct number from the table.
seartingChoice also needs to validate that they entered a number 1-4 and use a loop to prompt the user until they enter a valid number. If the user at any time hits the cancel button in a prompt we are supposed to give an alert of "Sorry you changed your mind". This is missing from my code because i haven't figured out how to do that.
When the program calculates everything and writes to the screen in the end it is supposed to write like "UsersName ordered #tickets for a total of dollaramt" but instead it writes "Null ordered null tickets for a total of $null." The following is what i have the the javascript part of the code:
var Prices = [60, 50, 40, 30];
var Usersname = prompt("Please enter your name");
while(Usersname = null)
{
Usersname = prompt("Please enter your name");
}
function numSeats () {
var seats = prompt("Please enter the number of seats you want to buy");
parseInt(seats);
while((seats = null)||(seats > 6))
{
seats = prompt("Please enter a number between 1 and 6");
parseInt(seats);
}
return seats;
}
var seatswanted = numSeats ();
function seatingChoice () {
var choice = prompt("Please enter where you would like your seats to be located by indicating the correct number from the table");
parseInt(choice)
while((choice = null)||(choice > 4))
{
choice = prompt("Please enter a number between 1 and 4, corresponding to your section choice");
parseInt(choice);
}
return choice;
}
var seating = seatingChoice();
var dollaramt = (seatswanted * Prices[seating-1]);
document.write(Usersname + " ordered " + seatswanted + "tickets for a total of " + "$" + dollaramt + ".");
Instead of comparison operator you are using assignment operator:
var Usersname = prompt("Please enter your name");
while(Usersname = null)
{
Usersname = prompt("Please enter your name");
}
and prompt return empty string if user wont input anything so instead of null compare it to empty string i.e, ''. so change this to:
var userName = prompt("Please enter your name");
while(userName == '')
{
userName = prompt("Please enter your name");
}
There are several errors in your code. You can try your code using jsfiddle (you can try your code properly modified here: http://jsfiddle.net/pu3s0n50/).
Your errors are that you assign Username, seats and choice instead of comparing them, i.e.:
while(Usersname = null)
should be
while(Usersname == null)
and
while((seats = null)||(seats > 6))
should be
while((seats == null)||(seats > 6))
and finally
while((choice = null)||(choice > 4))
should be
while((choice == null)||(choice > 4))
The error I do not know why this happening, but this maybe solve your issue.
var Usersname = '';
Usersname = prompt('Choose a Username:');
this works. And you need the same for the others prompt.
Also if you want seat in rang 1-6: while((seats = null)||(seats > 6)) its wrong. Change to ((seats <= 6) && (seats > 0))
Maybe this could help you.
Best regards.

Code won't run due to string length issue

Got a simple Javascript program here to accept and check a password. It should:
Ask you to enter a new password
Check the strength of the password which outputs a message of either weak or strong based on a length of <6 or >6.
Get you to re enter this password to enter the 'system'
Give you simple prompts or 2 random letters if the password is not correct.
Everything works except the strong/weak checker. It has a problem getting the length of passwordEntry since it apparently doesn't exist as an entity.
Any ideas would be much appreciated
var pass;
var main = function(){
strengthCheck((prompt("Please Choose a New Password to Begin"));
}
var strengthCheck = new function(passwordEntry){
score = 0;
// adds to the score variable depending on the length of the password
if(passwordEntry.length > 6{
score=(score+1);
}
//reads messages back stating how strong password is based on length
if(score=0){
console.log("Your Password is Weak");
}
else if(score=1){
console.log("Your Password is Strong");
}
var passContinue = prompt("Do you want to continue with this password? Yes or no?")
if(passContinue === "no" || passContinue === "No"{
main();
}
else{
pass = passwordEntry;
console.log("Your new password has been changed to " + pass);
passwordChecker(prompt("Thank You. Please Enter Your Password Below"));
}
}
var passwordChecker = function (attempt){
if(attempt == pass){
console.log("Correct password. The system has logged you on");
}
else{
//if the password is wrong, runs the incorrectpassword() function
console.log("Incorrect Password");
IncorrectPass();
}
}
}
var IncorrectPass = function (){
var clueanswer = prompt("Do You Want A Clue");
if(clueanswer === "Yes" ||clueanswer === "yes"){
console.log("I will give you two random letters");
// takes two random locations from the string array and reads them back
var randarray1 = Math.floor((Math.random()*7)+1);
var randarray2 = Math.floor((Math.random()*7)+1);
var randletter1 = pass[randarray1];
var randletter2 = pass[randarray2];
console.log(randletter1+" "+randletter2);
passwordChecker("Please try entering your password again");
}
else{
console.log("GoodBye");
}
}
main()
This part looks very wrong:
if(score=0){
console.log("Your Password is Weak");
}
else if(score=1){
console.log("Your Password is Strong");
}
You should use == or === instead of = which is used for assignment rather than comparison.
This doesn't make sense either:
var main = function(){
strengthCheck((prompt("Please Choose a New Password to Begin"));
}
There are three opening parentheses and only two closing ones. Smells like parser error.
Change this...
var strengthCheck = new function(passwordEntry){
to this...
var strengthCheck = function(passwordEntry){
When you use new, you're not using it to create a new function. You're using it to call the function as a constructor, which will return an object. (An empty object in your case.)
Also, you have many syntax errors in your code. Use a code validator like http://jshint.com as well as a beautifier like http://jsbeautifier.org to clean up your code.

Categories