I have written the simple html javascript code for validation of username and password , but the function authorize() is not getting called when the form is submitted. Can any one help me find out the mistake in my code. I know same question exists and I did followed them but I wasn't able to find my mistake. Thank You.
Below is my code
<script type="type/javascript" >
var users = {{"Username":"Sunny","Password":"Panzer"},{"Username":"Anjali","Password":"406460"}};
function authorize()
{
var username= document.getElementById("username").value;
var password = document.getElementById("password").value;
for(var i=0;i<users.length;i++)
{
if(users[i].Username==username && users[i].Password==password)
{
return true;
}
}
alert("invalid username or password");
return false;
}
</script>
<form action="enter_details.html" onsubmit="return authorize()" >
<center>Username <input type="text" id="username"></center><br><br>
<center>Password <input type="text" id="password"></center><br><br>
<center><input type="submit" id="login_button" value="Log In"></center>
</form>
You should enclose your JSON array in square (and not curly) brackets, like this:
var users = [{
"Username": "Sunny",
"Password": "Panzer"
},
{
"Username": "Anjali",
"Password": "406460"
}
];
function authorize() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
for (var i = 0; i < users.length; i++) {
if (users[i].Username == username && users[i].Password == password) {
return true;
}
}
alert("invalid username or password");
return false;
}
<form action="enter_details.html" onsubmit="return authorize()">
<center>Username <input type="text" id="username"></center><br><br>
<center>Password <input type="text" id="password"></center><br><br>
<center><input type="submit" id="login_button" value="Log In"></center>
</form>
We have two probleme here
1- the users mus be an array of object like :
var users = [{"Username":"Sunny","Password":"Panzer"},{"Username":"Anjali","Password":"406460"}];
2- when you insert your javascript code in html it is not : type="type/javascript" but type="text/javascript"
for resume your code must be like :
<script type="text/javascript">
var users = [{"Username":"Sunny","Password":"Panzer"},{"Username":"Anjali","Password":"406460"}];
function authorize()
{
var username= document.getElementById("username").value;
var password = document.getElementById("password").value;
for(var i=0;i<users.length;i++)
{
if(users[i].Username==username && users[i].Password==password)
{
return true;
}
}
alert("invalid username or password");
return false;
}
</script>
I hope it's help you
Try to use event listeners
Add a id attribute to form
<form id="myForm" action="enter_details.html" onsubmit="return authorize()" >
<center>Username <input type="text" id="username"></center><br><br>
<center>Password <input type="text" id="password"></center><br><br>
<center><input type="submit" id="login_button" value="Log In"></center>
</form>
And add event listener code in is
document.querySelector("#myForm")
.addEventListener("submit", function(eve) {
eve.preventDefault();
authorize();
}
If this didn't work try it on input button
document.querySelector("#login_button")
.addEventListener("click", function(eve) {
eve.preventDefault();
authorize();
}
var users = [{"Username":"Sunny","Password":"Sunny"},{"Username":"Anjali","Password":"406460"}];
function authorize(){
var username= document.getElementById("username").value;
var password = document.getElementById("password").value;
for(var i=0;i<users.length;i++)
{
if(users[i].Username==username && users[i].Password==password)
{
return true;
}
}
alert("invalid username or password");
return false;
}
<form onsubmit="authorize()" >
<center>Username <input type="text" id="username"></center><br><br>
<center>Password <input type="text" id="password"></center><br><br>
<center><input type="submit" id="login_button" value="Log In"></center>
</form>
If you want to use the callback function to submit the form, you need bind click on the
submit button and use event.preventDefault(); to prevent the page jumps in the callback, which is the form default action
<form>
<center>Username <input type="text" id="username"></center><br><br>
<center>Password <input type="text" id="password"></center><br><br>
<center><input type="submit" onclick="authorize(event)" id="login_button" value="Log In"></center>
</form>
<script>
var users = [{"Username":"Sunny","Password":"Panzer"},{"Username":"Anjali","Password":"406460"}];
function authorize(event)
{
event.preventDefault();
var username= document.getElementById("username").value;
var password = document.getElementById("password").value;
for(var i=0;i<users.length;i++)
{
if(users[i].Username==username && users[i].Password==password)
{
return true;
}
}
alert("invalid username or password");
return false;
}
</script>
I believe your main is problem is that variable users should be an array. Your current syntax is not valid for the definition of variable users, and will thrown an error (you can inspect the console to see it). Check the next example with that fix.
var users = [
{"Username":"Sunny","Password":"Panzer"},
{"Username":"Anjali","Password":"406460"}
];
function authorize()
{
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
for (var i = 0; i < users.length; i++)
{
if (users[i].Username == username && users[i].Password == password)
{
return true;
}
}
alert("invalid username or password");
return false;
}
<form onsubmit="return authorize()" >
<center>Username <input type="text" id="username"></center><br><br>
<center>Password <input type="text" id="password"></center><br><br>
<center><input type="submit" id="login_button" value="Log In"></center>
</form>
Even more, you can simplify the authorize() function a litle if you use Array.some():
function authorize()
{
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
let res = users.some(user => user.Username == username && user.Password == password);
if (!res)
alert("invalid username or password");
return res;
}
Related
I have a basic html form with password and verify password fields. I want to only allow users to continue if passwords match. If passwords do not match, I want there to be a notification to the user.
I think that what I currently have is close, but the JS still doesn't appear to do anything.
HTML
<form class="ajax-form" id="pwreset" method="post" onsubmit="return verifyPassword()" action="/set-password">
<div id="userinput">
<label for="username">Username</label>
<input type="text" id="username" name="username"/><br/>
<label for="new_password">Password</label>
<input type="Password" id="new_password" name="new_password"/><br/>
<label for="verifyPassword">Verify Password</label>
<input type="password" id="verifyPassword" name="verifyPassword"/><br/>
<input type="hidden" id="uuid" name="uuid" value="{{uuid}}"/>
<p><input class="button" type="submit" value="SUBMIT"></p>
</div>
</form>
JS
function verifyPassword() {
let pass1 = document.getElementById("new_password").value;
let pass2 = document.getElementById("verifyPassword").value;
let match = true;
if (pass1 != pass2) {
//alert("Passwords Do not match");
document.getElementById("new_password").style.borderColor = "#ff0000";
document.getElementById("verifyPassword").style.borderColor = "#ff0000";
match = false;
}
else {
alert("Passwords match.");
}
return match;
}
There are some issues that can come from putting the javascript call in the HTML.
In your case, the function was probably defined after the HTML, so the element didn't have access to it.
You can use this instead:
function verifyPassword() {
let pass1 = document.getElementById("new_password").value;
let pass2 = document.getElementById("verifyPassword").value;
let match = true;
if (pass1 != pass2) {
//alert("Passwords Do not match");
document.getElementById("new_password").style.borderColor = "#ff0000";
document.getElementById("verifyPassword").style.borderColor = "#ff0000";
match = false;
}
else {
alert("Passwords match.");
}
return match;
}
document.getElementById('pwreset').onsubmit = verifyPassword;
<form class="ajax-form" id="pwreset" method="post" action="/set-password">
<div id="userinput">
<label for="username">Username</label>
<input type="text" id="username" name="username" /><br/>
<label for="new_password">Password</label>
<input type="Password" id="new_password" name="new_password" /><br/>
<label for="verifyPassword">Verify Password</label>
<input type="password" id="verifyPassword" name="verifyPassword" /><br/>
<input type="hidden" id="uuid" name="uuid" value="{{uuid}}" />
<p><input class="button" type="submit" value="SUBMIT"></p>
</div>
</form>
Here is an example. I created a passwordGroup constructor to centralize the information. This way it's easier to write tests also.
var form = document.forms[0];
var pass1 = form.querySelector('[data-password]');
var pass2 = form.querySelector('[data-password-confirmation]');
var submitButton = form.querySelector('button[type="submit"]');
// PasswordGroup constructor
var PasswordGroup = function () {
this.password = '';
this.passwordConfirmation = '';
};
// method to update the passwords values
PasswordGroup.prototype.setValues = function(data) {
this.password = data.password;
this.passwordConfirmation = data.passwordConfirmation;
};
// method to check the password's equality
PasswordGroup.prototype.match = function() {
return !!(this.password
&& this.passwordConfirmation
&& this.password === this.passwordConfirmation);
};
/*
* Enable/disable the submit button if passwords do not match
*/
function validateSubmit() {
if(passwordGroup.match()) {
submitButton.removeAttribute('disabled');
} else {
submitButton.setAttribute('disabled', 'disabled');
}
}
// passwordGroup instance
var passwordGroup = new PasswordGroup();
// objecto to store the current values
var passwordsValues = {
password: '',
passwordConfirmation: '',
};
// event triggered after enter a new value in the password's field
var onPasswordChange = function(e) {
var target = e.target;
var targetValue = target.value;
if(target.dataset.hasOwnProperty('password')) {
passwordsValues.password = targetValue;
} else if (target.dataset.hasOwnProperty('passwordConfirmation')) {
passwordsValues.passwordConfirmation = targetValue;
}
passwordGroup.setValues(passwordsValues);
validateSubmit();
};
// event attribution
pass1.onkeyup = onPasswordChange;
pass2.onkeyup = onPasswordChange;
input {
display: block;
}
<form action="" name='account'>
<input type="text" placeholder="name" />
<input type="password" data-password placeholder="password"/>
<input type="password" data-password-confirmation placeholder="repeat password"/>
<button type="submit" disabled="disabled">Enviar</button>
</form>
<p data-message></p>
should i put "submit" instead "form_name" in the last block of code? what is the correct way?
thanks!
function check() {
var title = document.getElementById("title");
var content = document.getElementById("content");
if (title == "") {
alert("title is required");
return false;
}
if (content == "") {
alert("content is required");
return false;
}
var submit = document.getElementById("form_name");
submit.submit();
}
this is my form
<form action="#" method="post" id="form_name" name="form_name">
<input type="text" name="title" id="title" />
<textarea name="content" id="content" cols="30" rows="10"></textarea>
<input type="submit" value="Submit" id="submit" name="submit" onclick="return check();"/>
</form>
First you are selecting an element and acting like it is the value
var title = document.getElementById("title"); <-- DOM element
if (title == "") { <-- checking the DOM against a string.
You should be using .value to get what was entered.
Next you are submitting the form.... but you clicked on a submit button inside of the form so that will submit the form. So that is not needed.
function check() {
var title = document.getElementById("title").value;
var content = document.getElementById("content").value;
if (!title.trim().length) {
alert("title is required");
return false;
else if (!content.trim().length) {
alert("content is required");
return false;
}
return true
}
And never name anything submit, it just leads to problems.
In most recent browsers you have more power to use
function myFunction() {
var inpObj = document.getElementById("id1");
if (inpObj.checkValidity() == false) {
document.getElementById("demo").innerHTML = inpObj.validationMessage;
}else{
document.getElementById("demo").innerHTML = "";
}
}
<input id="id1" type="number" min="100" max="300" required>
<button onclick="myFunction()">OK</button>
<p id="demo"></p>
Reference:
https://www.w3schools.com/js/js_validation_api.asp
Html form driving me crazy.
I have a function that checks for mismatch passwords and if the username specified is already taken.
If you pass both of these checks then the form should submit, but it isn't.
It's not a db problem. I've checked that and it connects just fine.
The post in checkname and the post in the form both work when removing the double onsubmit argument. If anyone has any ideas please let me know :)
Here is link of the project I am currently working :
Functions and form:
function validatePassword() {
var pass1 = document.getElementById("password").value;
var pass2 = document.getElementById("confirm_password").value;
if (pass1 != pass2) {
alert("Passwords Do not match");
document.getElementById("password").style.borderColor = "#E34234";
document.getElementById("confirm_password").style.borderColor = "#E34234";
return false;
} else {
return true;
}
}
function checkname() {
var name = document.getElementById("username").value;
if (name) {
$.ajax({
type: 'post',
url: 'checkdata.php',
data: {
user_name: name,
},
success: function(response) {
$('#name_status').html(response);
if (response == "OK") {
return true;
} else {
return false;
}
}
});
} else {
$('#name_status').html("");
return false;
}
}
function checkall() {
var namehtml = document.getElementById("name_status").innerHTML;
if ((namehtml) == "OK") {
return true;
} else {
return false;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<font size=4><b>Customer sign up</b></font>
<form name="input" action="customer_insert.php" onsubmit=" return !!(validatePassword() & checkall());" method="post">
<br> Username: <input type="text" maxlength="45" name="username" id="username" onchange="checkname();" required="required">
<span id="name_status"></span>
<br> Password: <input type="password" maxlength="128" name="passwd1" id="password" required="required">
<br> Retype Password: <input type="password" maxlength="128" name="passwd2" id="confirm_password" required="required">
<br> First Name: <input type="text" maxlength="45" name="firstname" required="required">
<br> Last Name: <input type="text" maxlength="45" name="lastname" required="required">
<br> E-mail: <input type="email" name="email" required="required">
<input type="submit" name="Signup" value="Signup">
</form>
Fixed it. Problem was directly using checkname() in the condition results in undefined return and therefor, the condition could never be met. Now I take part of the old checkall() and integrated it with your validate method. This works. Thanks!
function validateForm(){
var a = validatePassword();
var b;
var namehtml=document.getElementById("name_status").innerHTML;
if(namehtml=="OK")
{
b = true;
}
else
{
b = false;
}
if(a && b){
return true;
}
else{
return false;
}
}
I have written code for a basic registration page to run on my webserver but javascript doesn't seem to be working in the html file. I do a form post with a javascript function to find errors but it seems to be completely ignoring the javascript code when I test it. Is there a problem with my javascript code or in the html code? My code is shown below.
<script type="text/javascript" language="Javascript">
function checkPasswordMatch(){
var password = document.getElementById("pass1").value;
var password2 = document.getElementById("pass2").value;
if(password != password2){
document.getElementById("divcheckpasswordmatch").innerHTML = "Passwords do not match!";}
else{
document.getElementById("divcheckpasswordmatch").innerHTML = "Passwords match.";}
}
// $(document).ready(function(){
// $("#pass2").keyup(checkPasswordMatch);
// })
function Error() {
var user = document.getElementById("user").value;
var pass1 = document.getElementById("pass1").value;
var pass2 = document.getElementById("pass2").value;
var email = document.getElementById("email").value;
if(user=""){
document.form1.username.focus();
document.getElementById("usernameerror").innerHTML = "Enter username.";
return false;
}
if(pass1=""){
document.form1.password1.focus();
document.getElementById("passworderror1").innerHTML = "Enter password.";
return false;
}
if(pass2=""){
document.form1.password2.focus();
document.getElementById("passworderror2").innerHTML = "Enter password.";
return false;
}
if(email=""){
document.form1.useremail.focus();
document.getElementById("emailerror").innerHTML = "Enter email";
return false;
}
}
</script>
</head>
<body>
<div id="link">
Home
<a align="right" href="signin">Sign-in</a>
</div>
<div id="header">
<center><h1><i>IMGCAPTURE</i></h1></center>
</div>
<div id="create">
<center><h2>Create Your Account</h2></center>
<form name="form1" action="account" onsubmit="return Error()" method="POST">
<div id="username"><center><h3>Enter Username: <input type="text" name="username" id="user" cols="15" rows="1"></input></h3></center></div>
<div id="usernameerror"></div>
<div id="password"><center><h3>Enter Password: <input type="password" name="password1" id="pass1" cols="15" rows="1"></input></h3></center></div>
<div id="passworderror1"></div>
<div id="confirmpassword"><center><h3>Re-Enter Password: <input type="password" name="password2" id="pass2" onChange="checkPasswordMatch()" cols="15" rows="1"></input></h3></center></div>
<div id="passworderror2"></div>
<div class="registrationFormAlert" id="divcheckpasswordmatch"></div>
<center><h3>Enter Email: <input type="email" name="useremail" id="email" cols="15" rows="1">
</input></h3></center>
<div id="emailerror"></div>
<center><input type="submit" value="Create Account" onclick="Error()"></input></center>
</form>
</div>
</body>
</html>
It may be that you are not calling the functions you are creating. So since you are not calling those functions with arguments, nothing inside them is going to happen. Let me know if this fixes it.
Also, stylistically you would want the Javascript code at the end of the HTML file.
Instead of binding your input name="password2" to the function by the onChange-tag, try binding it like this:
$(document).on('change', 'input[name="checkPasswordMatch"]', checkPasswordMatch);
function checkPasswordMatch() {
...
}
And in your HTML, remove the onChange tag:
<div id="confirmpassword">
<center>
<h3>
Re-Enter Password: <input type="password" name="password2" id="pass2" cols="15" rows="1"></input>
</h3>
</center></div>
It seems you've forgotten to include jQuery. If you use pure JS, it works :
<script type="text/javascript">
function checkPasswordMatch() {
var password = document.getElementById("pass1").value;
var password2 = document.getElementById("pass2").value;
if (password != password2) {
document.getElementById("divcheckpasswordmatch").innerHTML = "Passwords do not match!";
} else {
document.getElementById("divcheckpasswordmatch").innerHTML = "Passwords match.";
}
}
document.addEventListener('DOMContentLoaded', function() {
document.getElementById("pass2").addEventListener('keyup', checkPasswordMatch);
});
function Error() {
var user = document.getElementById("user").value;
var pass1 = document.getElementById("pass1").value;
var pass2 = document.getElementById("pass2").value;
var email = document.getElementById("email").value;
if (user = "") {
document.form1.username.focus();
document.getElementById("usernameerror").innerHTML = "Enter username.";
return false;
}
if (pass1 = "") {
document.form1.password1.focus();
document.getElementById("passworderror1").innerHTML = "Enter password.";
return false;
}
if (pass2 = "") {
document.form1.password2.focus();
document.getElementById("passworderror2").innerHTML = "Enter password.";
return false;
}
if (email = "") {
document.form1.useremail.focus();
document.getElementById("emailerror").innerHTML = "Enter email";
return false;
}
}
</script>
You probably want to use == or === in your if statements. You're assigning user, etc. to an empty string in your if conditionals.
if(user == ""){
document.form1.username.focus();
document.getElementById("usernameerror").innerHTML = "Enter username.";
return false;
}
I think the Jquery syntax IM using isn't correct, but not sure what is wrong. Maybe someone can give me a hand. So I have a HTML Login page, where it asks for user and pw. I want to save these 2 variables as session cookie.
Here is the HTML of the login:
<FORM NAME="cf">
<span class="auto-style1">Username:</span>
<input type="hidden" id="messageType" name="messageType" value="3">
<INPUT TYPE="text" id="userName" NAME="userName" size="20" style="width: 180px">
<br><span class="auto-style1">Password:</span> <INPUT TYPE="password" id="password" NAME="password" size="20" style="width: 180px">
<span lang="en-ca"> </span>
</FORM>
<INPUT TYPE="submit" id="btnSubmit" name="btnSubmit" Value="Sign In" style="width: 109px" class="auto-style2">
Here is the Javascript I have written:
$(document).ready(function () {
$("#btnSubmit").click(function () {
//collect userName and password
var messageType = $("#messageType").val();
var userName = $("#userName").val();
var password = $("#password").val();
var YouEntered;
var YouEntered2;
var cookie_name1 = "username";
var cookie_name = "password";
putCookie();
putCookie2();
auth(messageType, userName, password);
});
});
//Set Cookies username and password
function putCookie() {
if(document.cookie != document.cookie)
{index = document.cookie.indexOf(cookie_name1);}
else
{ index = -1;}
if (index == -1)
{
YouEntered=document.cf.userName.value;
document.cookie=cookie_name1+"="+YouEntered+"; expires=0"; //Expires when Session Ends
}
}
function putCookie2() {
if(document.cookie != document.cookie)
{index = document.cookie.indexOf(cookie_name);}
else
{ index = -1;}
if (index == -1)
{
YouEntered2=document.cf.password.value;
document.cookie=cookie_name+"="+YouEntered2+"; expires=0"; //Expires when Session Ends
}
}
If I use onclick in the HTML to run the putCookie functions, I can save the cookies, but it won't send to the server.
Any help or reason why it doesn't work is appreciated.
First change your function as
function putCookie(cookie_name1) {
if(document.cookie != your_cookie){
index = document.cookie.indexOf(cookie_name1);
}
else {
var YouEntered=document.cf.userName.value;
document.cookie=cookie_name1+"="+YouEntered+"; expires=0"; //Expires when Session Ends
}
}
and should call the function like
putCookie(cookie_name1);