I need help for a login page using JavaScript. So far I have following code:
function clicked() {
var user = document.getElementById('username');
var pass = document.getElementById('password');
var coruser = "admin";
var corpass = "admin";
if (user.value == coruser) {
if (pass.value == corpass) {
// Like you must login to see the page
} else {
window.alert("incorrect password or name");
}
} else {
window.alert("incorrect password or name");
}
}
I want it like after login show the page like you must login to see the page.
Any ideas?
Your function should look like this if you want to redirect user to your home page after checking the username.
function clicked() {
var user = document.getElementById('username');
var pass = document.getElementById('password');
var coruser = "admin";
var corpass = "admin";
if (user.value == coruser) {
if (pass.value == corpass) {
window.location.href = "your page url";
} else {
window.alert("incorrect password or name");
}
} else {
window.alert("incorrect password or name");
}
}
Note: this is not a way to handle authentication.
Related
please i want to know how to store the user input data in the registeration page then i pass it to login page and in login page i validate if the user write the right username and password or not(that already passed from registeration page)
here is my js code for registeration page:
<head>
<script>
//function to check if the passoword is matched
function checkpass() {
if (document.getElementById('psw').value ==
document.getElementById('psw-confirm').value) {
document.getElementById('message').style.color = 'green';
document.getElementById('message').innerHTML = 'Matched Passowrds';
} else {
document.getElementById('message').style.color = 'red';
document.getElementById('message').innerHTML = 'Those passwords didn’t match. Try again.';
}
}
//function to disable the submit button if the password is not matched
function check_pass() {
if (document.getElementById('psw').value ==
document.getElementById('psw-confirm').value) {
document.getElementById('submit').disabled = false;
} else {
document.getElementById('submit').disabled = true;
}
}
//function of cancel button
function goBack() {
window.history.back();
}
//function to only choose one gendre
function onlyOne(checkbox) {
var checkboxes = document.getElementsByName('check')
checkboxes.forEach((item) => {
if (item !== checkbox) item.checked = false
})
}
</script>
<link href="RegisterartinStyle.css" rel="stylesheet">
</head>
You can use sessionStorage to store temporary data like this...
sessionStorage.setItem('Username',username);
sessionStorage.setItem('Password',password);
To retreive the data from any of your pages...
var Username = sessionStorage.getItem('Username');
var Password = sessionStorage.getItem('Password');
Blow everything away...
sessionStorage.clear();
So I'm new to JS, and I wanna redirect the user to another page...
My code:
// Below function Executes on click of login button.
function validate() {
redirectTo =
window.location.protocol + window.location.host + "/dashboard.html";
var username = document.getElementById("userName").value;
var password = document.getElementById("passWord").value;
if (username == "admin" && password == "password") {
window.location = redirectTo; // Redirecting to other page.
return false;
} else {
alert("NANI!!!");
}
}
I know this is not a secure way to auth, but relax it's just a portfolio project
You should append the '//' after window.location.protocol which mentioned by #Vasan.
Using ES6 template strings would make it clear.
function validate() {
const redirectTo = `${window.location.protocol}//${window.location.host}/dashboard.html`;
const username = document.getElementById('userName').value;
const password = document.getElementById('passWord').value;
if (username === 'admin' && password === 'password') {
window.location = redirectTo; // Redirecting to other page.
return false;
} else {
alert('NANI!!!');
}
}
It should be window.location.href = redirectTo.
I use JavaScript for a simple function, however my redirection doesn't work. I thought it was because of the files, but they seem to be in the same folder. See below file structure:
Here is my relevant code:
function validate() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
if (username == "mr.X" && password == "x123456") {
alert("Login successfully");
window.location = "Dashboard.jsp"; // Redirecting to other page.
return false;
} else {
alert("You have inserted wrong credentials");
}
}
After a user sign in successfully, I want to use the User UID to verify the user has selected the right school, I have been able to achieve this task, but the problem is, I have to click the login button twice before an action takes effect.
var sbmit = document.getElementById("submit");
sbmit.onclick = function (e) {
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
var s = document.getElementById("school");
var school = s.options[s.selectedIndex].value;
e.preventDefault();
if (school == null || school == "") {
alert("Please select your school")
return false;
} else if (email == null || email == "") {
alert('email can\'t be empty')
return false;
} else if (password == null || password == "") {
alert("Password ca\'t be empty")
return false;
} else {
toggleSignIn();
//After signing in, use the user auth id to check if the user exist in the selected school
firebase.auth().onAuthStateChanged(user => {
if (user) {
ref = database.ref('/schools/')
userId = firebase.auth().currentUser.uid;
ref.child(school).orderByChild("AuthID").equalTo(userId).once("value", snapshot => {
if (snapshot.exists()) {
document.location.href = "/Result"
} else {
alert("You have selected the wrong school")
}
});
}
});
}
}
It is very unusual to have an onAuthStateChanged listener in a click handler like that. More likely you want something like:
...
} else {
toggleSignIn();
ref = database.ref('/schools/')
userId = firebase.auth().currentUser.uid;
ref.child(school).orderByChild("AuthID").equalTo(userId).once("value", snapshot => {
if (snapshot.exists()) {
document.location.href = "/Result"
} else {
alert("You have selected the wrong school")
}
});
}
By the way: if you can look up the school for the user with a query, is there any specific reason why you don't simply prepopulate that value for them in the form?
Your code has a flaw. onAuthStateChanged listener is attached every time the button is clicked. This could add multiple listeners and the same code triggered multiple times after each repeated click. onAuthStateChanged listener should be attached only once when the document is loaded. Your code should be something like:
var sbmit = document.getElementById("submit");
sbmit.onclick = function (e) {
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
var s = document.getElementById("school");
var school = s.options[s.selectedIndex].value;
e.preventDefault();
if (school == null || school == "") {
alert("Please select your school")
return false;
} else if (email == null || email == "") {
alert('email can\'t be empty')
return false;
} else if (password == null || password == "") {
alert("Password ca\'t be empty")
return false;
} else {
toggleSignIn();
}
}
document.onload = function () {
firebase.auth().onAuthStateChanged(user => {
if (user) {
ref = database.ref('/schools/')
userId = firebase.auth().currentUser.uid;
ref.child(school).orderByChild("AuthID").equalTo(userId).once("value", snapshot => {
if (snapshot.exists()) {
document.location.href = "/Result"
} else {
alert("You have selected the wrong school")
}
});
}
});
}
I assume toggleSignIn() function is used to sign in and will change the firebase AuthState on successful sign in.
I am trying to validate my company email-id's in sign up form...so that the form accepts only my company mail id...so now whats the problem here is after validating(ie; when we click submit button then we get an alert message) the form is getting refreshed and the entered values are cleared...so any help or suggestions so that it is not refreshed??thanks in advance...
My Javascript method is:
function submitAlbum() {
var frm = document.getElementById("frmRegistration");
//validateEmail(document.getElementById('email').value);
var email = document.getElementById('email').value;
var re = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\#[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
if (re.test(email)) {
if (email.indexOf('#bdisys.com', email.length - '#bdisys.com'.length) !== -1) {
// alert('Submission was successful.');
var r = confirm("Are You Sure You Want to add your details.");
if (r == true) {
frm.action = "signUpServlet?formidentity=doRegistration&checkboxStatus=" + checkboxStatus;
frm.submit();
}
}
else {
document.getElementById('email').focus();
alert('Email must be a Company e-mail address (your.name#bdisys.com).');
return false;
}
}
else {
document.getElementById('email').focus();
alert('Not a valid e-mail address.');
return false;
}
}
I think this will do the job.
<input type = "email" pattern ="^[a-z0-9._%+-]+#bdisys.com">
Check this bin
http://jsbin.com/dew/5/edit
You should bind your validation method to the submit event of your form.
Inside the validation method, stop the event to propagate if the field is invalid, or let it bubble if it's ok.
var frm = document.getElementById("frmRegistration");
frm.addEventListener('submit', validate, false);
var re = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\#[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
function validate(event) {
// validateEmail
var email = document.getElementById('email').value;
var confirmed = false;
if (re.test(email)) {
confirmed = true;
if (email.indexOf('#bdisys.com', email.length - '#bdisys.com'.length) !== -1) {
confirmed = confirm("Are You Sure You Want to add your details.");
}
} else {
document.getElementById('email').focus();
alert('Email must be a Company e-mail address (your.name#bdisys.com).');
}
if (!confirmed) {
event.preventDefault();
event.stopPropagation();
return false;
}
}
I suggest you to use jQuery to make your code simplier and before all portable.