Update to previous validation script (SCHOOL PROJECT) - javascript

Well, I have a slight problem in that I read part of the assignment wrong and actually need to have this login any valid email address format and forward it to the 2nd url (myaccount.html). I've tried several things, and while I can get it to login to both the ADMIN page & the MYACCOUNT page, if I put an invalid email in it still logs in (i.e. jdelor1965#yahoo.m). Any ideas?? Thanks...
// Chapters 3 & 4 - login.js (updated during week 3)
// Function called when the form is submitted.
// Function validates the form data and returns a pop-up if conditions are not met.
function validateForm() {
'use strict';
// Get references to the form elements:
var email = document.getElementById('email').value;
var password = document.getElementById('password').value;
var pattern = '/^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/';
// Validate!
if (email == 'admin#titanmusicstore.com' && password == 'LogMeIn')
{
window.location = "admin.html";
}
else if (pattern == '/^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/' && pattern == '/^\w+#[a- zA-Z_]+?\.[a-zA-Z]{2,3}$/')
{
window.location = "myaccount.html";
}
else
{
alert('Invalid or incorrect Email or Password!');
}
return false;
}
// End of validateForm() function.
JSFiddle: http://jsfiddle.net/FL2c4/
** I'm wondering if the problem is a conflict between the JavaScript being used and the "form action" in the HTML - either email/passowrd combo will bring me to the page listed in the "form action" field, but when I remove that information the login goes nowhere??
To clarify, this is a school project and not for use in the "real world"! Have received some really good help on here already, so thanks again to those who have assisted. This week, part of our assignment is to change our login validation script to direct the two (2) UID's to different locations. I've read all chapters, watched the videos, and have endlessly researched online but can't figure out how to get this to work - this is what I have, any suggestions or ideas would be greatly appreciated (I can also provide HTML as well - we have a couple pages for that, i.e. index, login, admin, & myaccount).
JavaScript:
// Script Week 2 - login.js
// Function called when the form is submitted.
// Function validates the form data and returns a pop-up if conditions are not met.
function validateForm() {
'use strict';
// Get references to the form elements:
var email = document.getElementById('email').value;
var password = document.getElementById('password').value;
var url = window.location.toLowerCase('login.html');
// Validate!
if (email == 'admin#titanmusicstore.com' && password == 'LogMeIn')
{
window.location = "admin.html";
}
else if (email == 'jdelor1965#yahoo.com' && password == 'LogMeIn')
{
window.location = "myaccount.html";
return true;
}
else
{
alert('Please fill out form accurately - Incorrect UID or Password!');
return false;
}
}
// End of validateForm() function.
// Function called when the window has been loaded.
// Function needs to add an event listener to the form.
function init() {
'use strict';
// Confirm that document.getElementById() can be used:
if (document && document.getElementById) {
var loginForm = document.getElementById('loginForm');
loginForm.onsubmit = validateForm;
}
}
// End of init() function.
// Assign an event listener to the window's load event:
window.onload = init;

New code
// Script Week 2 - login.js
// Function called when the form is submitted.
// Function validates the form data and returns a pop-up if conditions are not met.
function validateForm() {
'use strict';
// Get references to the form elements:
var email = document.getElementById('email').value;
var password = document.getElementById('password').value;
// var url = window.location.toLowerCase('login.html'); DELETE -- does nothing
// Validate!
if (email == 'admin#titanmusicstore.com' && password == 'LogMeIn') {
window.location = "http://talk.collegeconfidential.com/";
} else if (email == 'jdelor1965#yahoo.com' && password == 'LogMeIn') {
window.location = "http://disney.com";
} else {
alert('Please fill out form accurately - Incorrect UID or Password!');
}
return false;
}
// End of validateForm() function.
// Function called when the window has been loaded.
// Function needs to add an event listener to the form.
function init() {
'use strict';
// Confirm that document.getElementById() can be used:
if (document && document.getElementById) {
var loginForm = document.getElementById('loginForm');
loginForm.onsubmit = validateForm;
}
}
// End of init() function.
// Assign an event listener to the window's load event:
window.onload = init;
You need to return false from the validateForm function false every time to stop the form from submitting on its own. Since it's false under every condition, I moved that statement to the end of the function.
I changed the URLs so they would work in FIDDLE.
I also changed your fiddle from onLoad to No wrap so your own onload handler would work.

change your fiddle to HEAD instead of onload
You need to remove all return statements and have ONE return false in the validate like this http://jsfiddle.net/mplungjan/mt8Vb/
Like this
window.onload = function () { // when the page has loaded
// find the form and attach an event handler to the submit
document.getElementById('loginForm').onsubmit = function () {
// Get references to the form elements:
var email = document.getElementById('email').value;
var password = document.getElementById('password').value;
// Validate!
if (email == 'xxx...musicstore.com' && password == 'LogMeIn') {
window.location = "admin.html";
} else if (email == 'yyy...yahoo.com' && password == 'LogMeIn') {
window.location = "myaccount.html";
} else {
alert('Please fill out form accurately - Incorrect UID or Password!');
}
return false; // you never want to actually submit the form
}
}

Related

Window.location.redirect only works while debugging

I created a function to check different values in input fields. If all requirements are fulfilled I want to route the user to another page. I struggled a lot and now it only works in firefox while I´m debugging, otherwise it stays on the initial pag.
function login() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
var password2 = document.getElementById("password2").value;
var email = document.getElementById("email").value;
var checkBox = document.getElementById("conditions").value;
if (password != password2) {
alert("Passwords don't match");
} else if (password.length < 6) {
alert("The password has to be atleast 6 characters");
} else if (checkBox != "on") {
alert("You have to agree to the terms");
} else if (username.length < 1) {
alert("Enter a username");
} else if (password == password2 && checkBox == "on") {
window.location.replace("url");
} else {
alert("Something went wrong");
}
}
If you want to load another webpage in current window by modifying the window.location object, then you can do it by few ways:
window.location.replace
window.location.replace('https://your-url.com');
window.location.assign
window.location.assign('https://your-url.com');
The Location.assign() method causes the window to load and display the document at the URL specified. After the navigation occurs, the user can navigate back to the page that called Location.assign() by pressing the "back" button.
window.location.href
window.location.href = 'https://your-url.com';
In first two methods, there might some problems in few cases and these might not work
example:
If the assignment can't happen because of a security violation, a DOMException of the SECURITY_ERROR type is thrown. This happens if the origin of the script calling the method is different from the origin of the page originally described by the Location object, mostly when the script is hosted on a different domain.
If the provided URL is not valid, a DOMException of the SYNTAX_ERROR type is thrown.
you can use any one of these.

How to redirect to another page using javascript

I am trying to find a way to redirect to another page using javascript once the user presses the submit form. I know how to do it using HTML but I can not get it to work here. The form submits but then it won't take you anywhere. I have tried a couple of different things I found online but nothing seems to work.
Here is my code
"use strict";
// global variables
var profile = {};
var formValidity = true
// validate entered password
function validateEmail() {
var email1Input = document.getElementById("email");
var email2Input = document.getElementById("email_retype");
email1Input.value = email1Input.value.toLowerCase();
email2Input.value = email2Input.value.toLowerCase();
var errorDiv = document.getElementById("emailError");
try {
if (email1Input.value.localeCompare(email2Input.value) !== 0) {
throw "The e-mails do not match";
}
// remove any password error styling and message
email1Input.style.background = "";
email2Input.style.background = "";
errorDiv.style.display = "none";
errorDiv.innerHTML = "";
}
catch(msg) {
// display error message
errorDiv.style.display = "block";
errorDiv.innerHTML = msg;
// change input style
email1Input.style.background = "rgb(255,233,233)";
email2Input.style.background = "rgb(255,233,233)";
formValidity = false;
}
}
/* create event listeners */
function createEventListeners(){
var form = document.getElementsByTagName("form")[0];
if (form.addEventListener){
form.addEventListener("submit", validateForm, false);
}else if (form.attachEvent) {
form.attachEvent("onsubmit", validateForm);
}
}
/* validate form */
function validateForm(evt) {
if(evt.preventDefault) {
evt.preventDefault(); // prevent form from submitting
}else {
evt.returnValue = false; // prevent form from submitting in IE8
}
formValidity = true; // reset value for revalidation
validateEmail();
if (formValidity === true) {
document.getElementsByTagName("form")[0].submit();
location.href = "about.php";
}
}
/* run setup functions when page finishes loading */
if (window.addEventListener) {
window.addEventListener("load", createEventListeners, false);
}else if (window.attachEvent) {
window.attachEvent("onload", createEventListeners);
}
You are unable to submit the form and then redirect. because the submit will redirect to the page defined in the form's "action". I see that your javascript function is just validating the fields
Example:
<form action = "action_page.php" method = "get">
This should help some... your if statements, such as:
if(window.addEventListener){ ... } || if(document.addEventListener){ ... }
will not execute the way you are expecting in your current implementation. If you would like to set up your event handlers when the window loads, you'd be better of implementing something like:
window.onload = createEventListeners;
// or
window.onload = function() {
var form = document.getElementsByTagName("form")[0];
form.addEventListener("submit", validateForm, false);
}
Here is some documentation on window.onload
https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onload
and submitting an HTML with examples using javascript event handlers
https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit_event
Although, if you really need/want to manually redirect the user using js, one way you can achieve this through window.location:
https://developer.mozilla.org/en-US/docs/Web/API/Window/location
I normally wouldn't normally recommend redirecting users this way, but I don't know enough about your code entirely, and it's still something that is very good to understand.

jquery code working but not the first time

I'm trying to build a small login system using jquery (since it is for testing purposes only and the user and password won't change) So i made a form and when you click the button i test whether the details are correct. if so you will get send to the next page. If not i give an alert.
It's working but i have something weird. The first time you visit the site and fill in the details it does nothing. The second time (after submitting) it works like it should.
Does someone know why?
Here is the code:
function controllogin() {
event.preventDefault();
var username = $("#gebruikersnaam").val()
var password = $("#wachtwoord").val()
if (username=="leerkrachten" && password=="leerkrachten") {
alert("welkom leerkrachten");
goToUrl();
}
else if (username=="leerling" && password=="leerling") {
alert("welkom leerling");
}
else {
alert("verkeerde gegevens ingevuld");
}
};
function goToUrl() {
alert("zoeken naar pagina");
window.location = 'leerkrachten/vakken.html';
};
Instead of onclick="controllogin();" try something like this:
$('document').ready(function() {
$('#submit').click(function(event) {
event.preventDefault();
var username = $("#gebruikersnaam").val()
var password = $("#wachtwoord").val()
if (username==="leerkrachten" && password==="leerkrachten") {
alert("welkom leerkrachten");
goToUrl();
}
else if (username==="leerling" && password==="leerling") {
alert("welkom leerling");
}
else {
alert("verkeerde gegevens ingevuld");
}
});
});
Also use === instead of == as operators to compare the strings, it prevents you from some weird results when comparing different types. Maybe that's why it doesn't work the first time, but does the second time. Otherwise I don't know why this happens.
But actually I'd have to say: NEVER do client-side login validation and NEVER do login validation with an unencrypted password (not even server-side)!

Get the id of element focus is moving to in jQuery.blur event?

I've written some code using jQuery to do an ajax call and display a message on the page when the user moves focus away from a field. My field is called txtLogin and the user types in some text and clicks a button to create a new user account in a database using the given txtLogin value.
The issue is that a valid value must contain four letters, a dash, and then four more letters. My client insists that the form should have two fields, one for the first four letters, and another for the second four letters.
Suppose that these two fields are called txtLogin0 and txtLogin1. I still want to do an ajax call when the user moves focus away from the field, but the ajax call should not be invoked when the user moves from one of the two fields to the other!
My current code looks like this.
$('#txtLogin').blur(function() {
var login = $(this).val();
var isValid = testLogin(login);
if (!isValid) alert('Login is invalid');
});
I imagine my new code looking like this:
$('#txtLogin0').add('#txtLogin1').blur(function() {
var focusId = The Id of the newly focused element
if (focusId==='txtLogin0' || focusId==='txtLogin1) return
var login = $(#txtLogin0').val() + '-' + $('#txtLogin1').val();
var isValid = testLogin(login);
if (!isValid) alert('Login is invalid');
});
How can I get the id of the element that the focus moves to in the jQuery.blur event?
A simple hack is to create two var to store the current and previous element in onfocus and onblur and call the validate method inside a timer which will be triggered in 0 milli seconds.. Try below code and I think it is close to what you want.
DEMO
var prevEl, curEl;
$(document).ready(function() {
$('#txtLogin0, #txtLogin1').blur(function() {
prevEl = this.id;
setTimeout(validateLogin, 0);
}).focus(function() {
curEl = this.id;
});
});
function validateLogin() {
if ((prevEl === 'txtLogin0' && curEl === 'txtLogin1') || (curEl === 'txtLogin0' && prevEl === 'txtLogin1')) {
return;
}
prevEl = ''; curEl = '';
var login = $('#txtLogin0').val() + '-' + $('#txtLogin1').val();
var isValid = testLogin(login);
if (!isValid) alert('Login is invalid');
}
function testLogin(txt) {
return false;
}
var focusId = $(this).attr('id');

How redirect cancel function in Javascript

I'm not a programmer. I don't want to protect with a strong secure code my page. I just need one option I'm missing in my code and can't figure out how to add it.
<script language="Javascript">
<!--
var password = "lala"
var x = prompt("","")
if (x.toLowerCase() == password) {
location = "http://google.com";
}
else {
alert("Fail")
location = "http://facebook.com"
}
//-->
</script>
As you can see it's so dump but I need it. When I press Cancel button instead of writing true or false text, website still opens. I want to include in this script cancel button function (control it, you know) whitch would redirect to another website if press on it (as it is with true or false functions). I don't want to creat a special button or an input for it.
Update: I would like to include this script in a page which i am redirecting to. Could anyone tell me:
1. How can i modify this script to make it work only once?
2. Is it anything to do with browser's cookies?
p.s. Done :)
If the user presses cancel, prompt will return null. So do like this:
if(x == null) // Cancel
{
alert('Cancel');
}
else if (x.toLowerCase() == password) { // Correct password
location = "http://google.com";
}
else { // Wrong password
alert("Fail")
location = "http://facebook.com"
}
However, I'm not sure if all browsers will return null when the user presses cancel. (I have tested in Opera)
Try
var x = prompt("","");
if( x == null || x == '')
return;
if (x.toLowerCase() == password) {
location = "http://google.com";
}
else {
alert("Fail")
location = "http://facebook.com"
}
To redirect your browser to a URL use following snippet in your Javascript:
top.location.href = "http://google.com";

Categories