How can I verify form passwords match using JavaScript? - javascript

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>

Related

Why the paragraphs arent showing up when inputs are empty

im pretty new to coding and i wanted to try to make a register form and use javascript to check if any of the forms are empty. I tried to make it using DOM but it seems that its not working. If anyone can help me i will be really thankful.
js code:
let btnCheck = document.querySelector('#claim');
let input = document.querySelectorAll('input');
let fname = document.querySelector('#fname');
let lname = document.querySelector('#lname');
let email = document.querySelector('#email');
let password = document.querySelector('#password');
function checkForBlank(){
if (document.querySelector('#fname').value == ""){
fname.innerHTML = 'First Name cannot be empty'
}
if (document.querySelector('#lname').value == ""){
lname.innerHTML = 'Last Name cannot be empty'
}
if (document.querySelector('#email').value == ""){
email.innerHTML = "Looks like this is not an email"
}
if (document.querySelector('#password').value ==""){
password.innerHTML = 'Password cannot be empty'
}
}
btnCheck.addEventListener('click', checkForBlank());
html code:
<form>
<input type='text' placeholder="First Name">
<p id='fname'></p>
<input type='text' placeholder="Last Name">
<p id='lname'></p>
<input type='text' placeholder="Email Address">
<p id='email'></p>
<input type='password' placeholder="Password">
<p id='password'></p>
</form>
Your code does not check to see if the form input field is empty currently. You would want to get reference to the input and check to see if that is empty.
<form>
<input id="fname-input" type="text" placeholder="First Name" />
<p id="fname"></p>
<input id="lname-input" type="text" placeholder="Last Name" />
<p id="lname"></p>
<input id="email-input" type="text" placeholder="Email Address" />
<p id="email"></p>
<input id="password-input" type="password" placeholder="Password" />
<p id="password"></p>
</form>
const btnCheck = document.querySelector('#claim');
const fname = document.querySelector('#fname');
const fnameInput = document.querySelector('#fname-input');
const lname = document.querySelector('#lname');
const lnameInput = document.querySelector('#lname-input');
const email = document.querySelector('#email');
const emailInput = document.querySelector('#email-input');
const password = document.querySelector('#password');
const passwordInput = document.querySelector('#password-input');
function checkForBlank() {
if (fnameInput.value == "") {
fname.innerHTML = "First Name cannot be empty";
}
if (lnameInput.value == "") {
lname.innerHTML = "Last Name cannot be empty";
}
if (emailInput.value == "") {
email.innerHTML = "Looks like this is not an email";
}
if (passwordInput.value == "") {
password.innerHTML = "Password cannot be empty";
}
}
btnCheck.addEventListener('click', checkForBlank);
Additionally, you need to pass a function reference to addEventListener instead of invoking the function.
btnCheck.addEventListener('click', checkForBlank()); // WRONG
btnCheck.addEventListener('click', checkForBlank); //RIGHT
Note: I would recommend to rather (or additionally) use the required property of html elements https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/required
There are multiple things that you need to refactor
It would be better to create a new HTML element for errors with different classes.
As you are wrapping the inputs in the form element, So you need to preventDefault.
For clickListener you need to pass the function reference only, no need to execute the function
// INPUTS
let btnCheck = document.querySelector('#claim');
let fname = document.querySelector('#fname');
let lname = document.querySelector('#lname');
let email = document.querySelector('#email');
let password = document.querySelector('#password');
// INPUT ERRORS
let fnameError = document.querySelector('#fname-error');
let lnameError = document.querySelector('#lname-error');
let emailError = document.querySelector('#email-error');
let passwordError = document.querySelector('#password-error');
function checkForBlank(e) {
e.preventDefault();
console.log(fname.value);
if (fname.value === "") {
fnameError.textContent = 'First Name cannot be empty'
} else {
fnameError.textContent = ''
}
if (lname.value === "") {
lnameError.textContent = 'Last Name cannot be empty'
} else {
lnameError.textContent = ''
}
if (email.value === "") {
emailError.textContent = "Looks like this is not an email"
} else {
emailError.textContent = ''
}
if (password.value === "") {
passwordError.textContent = 'Password cannot be empty'
} else {
passwordError.textContent = ''
}
}
btnCheck.addEventListener('click', checkForBlank);
p.error{
color: red;
font-size: 12px;
padding: 0;
margin: 4px 0 8px 0;
}
<form>
<input type='text' placeholder="First Name" id='fname'>
<p class="error" id="fname-error"></p>
<input type='text' placeholder="Last Name" id='lname'>
<p class="error" id="lname-error"></p>
<input type='text' placeholder="Email Address" id='email'>
<p></p>
<p class="error" id="email-error"></p>
<input type='password' placeholder="Password" id='password'>
<p></p>
<p class="error" id="password-error"></p>
<button id="claim"> check </button>
</form>

Disable Button for form

I have a simple form. Ive tried to disable the the submit button until fields have been filled out, however it seems to not be working. can anyone point me in the right direction to what I'm doing wrong.
<form id="casmansForm">
Name: <input type="name" id="userName" class="inputs"><br>
Email: <input type="name" id="userName" class="inputs"><br>
Text: <input type="name" id="userName" class="inputs"><br>
<input type="submit" id="userSubmit" disabled><br>
</form>
<div id='alertMessage'></div>
var userName = document.getElementById('userName');
var userEmail = document.getElementById('userEmail');
var userText = document.getElementById('userText');
var userSubmit = document.getElementById('userSubmit');
var alertMessage = document.getElementById('alertMessage');
function checkForm(){
if(userName.value == "" || userEmail.value == "" || userText.value == "")
{
alertMessage.innerHTML = 'Please fill in form correctly';
userSubmit.disabled = true;
return false;
} else {
alertMessage.innerHTML = 'Thank you for filling in form';
userSubmit.disabled = false;
return true;
}
}
userName.addEventListener("blur",checkForm,false);
userEmail.addEventListener("blur",checkForm,false);
userText.addEventListener("blur",checkForm,false);
Your main issue is that you have used the same id on more than one element. ids must be unique within a document.
Also, return false is not doing anything for you in this context.
Lastly, don't use .innerHTML when you aren't supplying any HTML, use textContent for that instead.
var userName = document.getElementById('userName');
var userEmail = document.getElementById('userEmail');
var userText = document.getElementById('userText');
var userSubmit = document.getElementById('userSubmit');
var alertMessage = document.getElementById('alertMessage');
function checkForm(){
if(userName.value == "" || userEmail.value == "" || userText.value == "") {
alertMessage.textContent = 'Please fill in form correctly';
userSubmit.disabled = true;
} else {
alertMessage.textContent = 'Thank you for filling in form';
userSubmit.disabled = false;
}
}
userName.addEventListener("blur",checkForm,false);
userEmail.addEventListener("blur",checkForm,false);
userText.addEventListener("blur",checkForm,false);
<form id="casmansForm">
Name: <input type="name" id="userName" class="inputs"><br>
Email: <input type="name" id="userEmail" class="inputs"><br>
Text: <input type="name" id="userText" class="inputs"><br>
<input type="submit" id="userSubmit" disabled>
</form>
<div id='alertMessage'></div>

Javascript How to use multiple function in html form submission to validate

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

Javascript Form Validation Event

)
I am trying to validate a form using Javascript, i would like the span to update when the string length is a certain amount of characters
<form id="contact">
<input id="name" name="name" type="text" class="feedback-input" placeholder="Name"/> <span id="spanName"> </span>
<input name="email" type="text" class="feedback-input" placeholder="Email" />
<textarea name="text" class="feedback-input" placeholder="Message..."></textarea>
<input type="submit" value="SUBMIT"/>
</form>
window.onload = function () {
var name = document.getElementById("name");
var nameVal = name.value;
var spanName = document.getElementById("spanName");
spanName.innerHTML = "✗";
name.addEventListener('keydown', function () {
validate();
});
function validate() {
console.log(name);
console.log(nameVal);
if (nameVal.length > 0) {
spanName.innerHTML = "✔";
} else if (nameVal.length > 8) {
spanName.innerHTML = "name is to long";
} else {
spanName.innerHTML = "yolo";
}
console.log(nameVal);
}
}
Variable scope is important.
Inside window.onload you declare three variables … and only use name once, to assign a value to onkeyup.
Inside validate you use name, which is a global variable already provided by the browser (it is not the variable you declared that is local to the other function). This is a string, so its length never changes.
// Create an IIFE to create a new (non-global) scope for all your variables.
(function() {
// Declare your variables at a level all the functions can reach them
var spanName, name;
// Get the DOM elements when the load event fires
function getDomElements() {
name = document.getElementById("contact").elements.name;
spanName = document.getElementById("spanName");
name.addEventListener("keyup", validate);
}
window.addEventListener("load", getDomElements);
// Define your validation function
// Check the VALUE of the form control, not the form control itself
function validate() {
// Make sure you exclude values you want a later condition to match
if (name.value.length > 0 & name.value.length <= 8) {
spanName.innerHTML = "✔";
} else if (name.value.length > 8) {
spanName.innerHTML = "name is to long";
} else {
spanName.innerHTML = "yolo";
}
}
})();
<form id="contact">
<input id="name" name="name" type="text" class="feedback-input" placeholder="Name" /> <span id="spanName"> </span>
<input name="email" type="text" class="feedback-input" placeholder="Email" />
<textarea name="text" class="feedback-input" placeholder="Message..."></textarea>
<input type="submit" value="SUBMIT" />
</form>
Sorry, this is an answer:
var contact, spanName;
window.onload = function () {
spanName = document.getElementById("spanName");
contact = document.getElementById("name");
contact.onkeyup = validate;
}
function validate() {
var name = contact.value;
var length = name.length;
if (length > 0 && length <=8) {
spanName.innerHTML = "✔";
} else if (length > 8) {
spanName.innerHTML = "name is to long";
} else {
spanName.innerHTML = "yolo";
}
}
Does it work to you?

Javascript not working in html file

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

Categories

Resources