So I'm trying to check if the user inputs the same email address and password twice in a signup form using javascript. It shouldn't let them sign up if they don't match, however only the portion of the passwords is working and the email isn't working. Here's my code:
<form>
<input type="email" name="fname" placeholder="Email Adress" required="required" class="input-txt" id="email1">
<input type="email" name="fname" placeholder="Confirm Email Adress" required="required" class="input-txt" id="email2">
<br><br>
<input id="password" type="password" name="fname" placeholder="Create Password" required="required" class="input-txt">
<input id="confirm_password" type="password" name="fname" placeholder="Confirm Password" required="required" class="input-txt"><br>
<button type="submit" class="btn">Sign up</button>
</form>
<script>
function validateMail() {
if(first_email.value != second_email.value) {
email2.setCustomValidity("Emails Don't Match");
} else {
email2.setCustomValidity('');
}
}
email1.onchange = validateMail;
email2.onkeyup = validateMail;
var password = document.getElementById("password")
, confirm_password = document.getElementById("confirm_password");
function validatePassword(){
if(password.value != confirm_password.value) {
confirm_password.setCustomValidity("Passwords Don't Match");
} else {
confirm_password.setCustomValidity('');
}
}
password.onchange = validatePassword;
confirm_password.onkeyup = validatePassword;
</script>
You need to assign var in top of the script:
var first_email = document.getElementById("email1")
, second_email = document.getElementById("email2")
, password = document.getElementById("password")
, confirm_password = document.getElementById("confirm_password");
Related
How to disable submit button until the user enters all fields and also how to use event listener on submit form.
<form action='index.html' id="form-user" onsubmit="init()">
<input type="text" name="username" id="username" placeholder="username">
<input type="email" name="email" id="email" placeholder="email">
<input type="password" name="password" id="password" placeholder="password">
<button type="submit" name="submit" id='button-send'>SUBMIT</button>
</form>
const init = function () {
let username = document.getElementById("username").value;
let password = document.getElementById("password").value;
let email = document.getElementById("email").value;
alert(username,password,email)
};
Jsfiddle link
Set up a validation object with booleans to record if all your values have met validation.
Then I'd loop through all your inputs and add an event listener to each of them. In this example I've checked to see if each has at least one character in them, but you might want to expand on this.
Finally, loop through your validation object and check if all the values are true. If they are, remove the disabled attribute from the button.
let inputs = document.querySelectorAll('input');
let buttonSend = document.getElementById('button-send');
let inputValidator = {
"username": false,
"email": false,
"password": false
}
inputs.forEach((input) => {
input.addEventListener('input', () => {
let name = event.target.getAttribute('name');
if (event.target.value.length > 0) {
inputValidator[name] = true;
} else {
inputValidator[name] = false;
};
let allTrue = Object.keys(inputValidator).every((item) => {
return inputValidator[item] === true
});
if (allTrue) {
buttonSend.disabled = false;
} else {
buttonSend.disabled = true;
}
})
})
<form action='index.html' id="form-user">
<input type="text" name="username" id="username" placeholder="username">
<input type="email" name="email" id="email" placeholder="email">
<input type="password" name="password" id="password" placeholder="password">
<button type="submit" name="submit" id='button-send' disabled>SUBMIT</button>
</form>
This is probably not what you are looking for but you can achieve almost the same effect by simply using the required attribute in your input fields:
<form action='index.html' id="form-user">
<input type="text" name="username" id="username" placeholder="username" required>
<input type="email" name="email" id="email" placeholder="email" required>
<input type="password" name="password" id="password" placeholder="password" required>
<button type="submit" name="submit" id='button-send' >SUBMIT</button>
</form>
Using the onBlur event will ensure the user has visited each field. You may also want to check the field contains a value, for that you can add the HTML required attribute.
var isDirty = {
username: false,
password: false,
email: false
}
const init = function() {
let incompleteItems = getIncompleteItems();
if(incompleteItems.length > 0) {
alert(`${incompleteItems} requires a value.`);
return;
}
let username = document.getElementById("username").value;
let password = document.getElementById("password").value;
let email = document.getElementById("email").value;
alert(`values: ${username}, ${email}, ${password}`);
};
const onChange = function(e) {
isDirty[e.id] = true;
}
const getIncompleteItems = function() {
let incomplete = "";
for (const [key, value] of Object.entries(isDirty)) {
if(value === false) {
if(incomplete.length > 0) {
incomplete += `, ${key}`;
}
else {
incomplete = key;
}
}
}
return incomplete;
}
<form method='GET' id="form-user" onsubmit="init()">
<input type="text" name="username" id="username" placeholder="username" onBlur="onChange(this)">
<input type="email" name="email" id="email" placeholder="email" onBlur="onChange(this)">
<input type="password" name="password" id="password" placeholder="password" onBlur="onChange(this)">
<button type="submit" name="submit" id='button-send'>SUBMIT</button>
</form>
Create a validation function which will check all the validations and sets the disabled property of the button if validation fails and vice versa. Call the validation function on every change of all the fields.
You can use oninput event
<input type="text" oninput="validate()">
I made a simple page to validate input. but even my input matches the regular expressions, all three alerts still happen. Could you please help me figure it out? Thanks
<script>
function validate() {
var tel = document.getElementById("tel").innerHTML;
var email = document.getElementById("email").innerHTML;
var pcode = document.getElementById("pcode").innerHTML;
var tvalid = /^(\d{3}-\d{3}-\d{3}-\d{4})$/;
if(!tvalid.test(tel)) {
alert("Not a valid Phone Number");
}
if (!(/#gmail\.com$/.test(email)) && !(/#hotmail\.com$/.test(email)) && !(/#outlook\.com$/.test(email)) ) {
alert("Not a valid email");
}
var pvalid = /^([A-Z][A-Z]\d{2}-[a-z]\d[A-Z]\d)$/;
if(!pvalid.test(pcode)){
alert("Not a valid postal code.");
}
}
</script>
html
<label for="tel">Phone Number</label>
<input type="tel" id="tel" name="tel" placeholder="Format: 001-123-456-7890" required><br>
<input type="tel" id="tel" name="tel" placeholder="Format: 001-123-456-7890" required><br>
<label for="email">Email Address</label>
<input type="email" id="email" name="email" placeholder="xxx#(gmail/hotmail/outlook).com" required><br>
<label for="pcode">Postal Code</label>
<input type="text" id="pcode" name="pcode" placeholder="AA11-c1V2"><br>
<button type = "button" id="submit" onclick="validate()">Validate</button>
The reason why your code returns invalid for all inputs is because youre not actually testing it against the entered input, rather an empty string ''.
.innerHTML will return an empty string since there is no HTML between the start and end of your input tags.
To get the value of a control try using something like var tel = document.getElementById("tel").value;
This will return the actual user input.
So your code should look like this:
function validate() {
var tel = document.getElementById("tel").value;
var email = document.getElementById("email").value;
var pcode = document.getElementById("pcode").value;
var tvalid = /^(\d{3}-\d{3}-\d{3}-\d{4})$/;
if (!tvalid.test(tel)) {
alert("Not a valid Phone Number");
}
if (!(/#gmail\.com$/.test(email)) && !(/#hotmail\.com$/.test(email)) && !(/#outlook\.com$/.test(email))) {
alert("Not a valid email");
}
var pvalid = /^([A-Z][A-Z]\d{2}-[a-z]\d[A-Z]\d)$/;
if (!pvalid.test(pcode)) {
alert("Not a valid postal code.");
}
}
<label for="tel">Phone Number</label>
<input type="tel" id="tel" name="tel" placeholder="Format: 001-123-456-7890" required><br>
<input type="tel" id="tel" name="tel" placeholder="Format: 001-123-456-7890" required><br>
<label for="email">Email Address</label>
<input type="email" id="email" name="email" placeholder="xxx#(gmail/hotmail/outlook).com" required><br>
<label for="pcode">Postal Code</label>
<input type="text" id="pcode" name="pcode" placeholder="AA11-c1V2"><br>
<button type="button" id="submit" onclick="validate()">Validate</button>
This question already has an answer here:
Why is the value of my input always empty if I store it in a variable?
(1 answer)
Closed 2 years ago.
Ive got this piece of code:
<form class="register" id="reg-form">
<input type="text" class="input-box" placeholder="Username" id="username" required><br><br>
<input type="text" class="input-box" placeholder="Full Name" id="name" required><br><br>
<input type="email" class="input-box" placeholder="Email" id="email" required><br><br>
<input type="password" class="input-box" placeholder="Password" id="password" required><br><br>
<input type="password" class="input-box" placeholder="Repeat Password" id="passwordrep" required><br><br><br>
<button class="btn-rounded-md black" id="reg-btn">Register</button>
</form>
and this js:
window.onload = function() {
var email = document.getElementById('email').value;
var password = document.getElementById('password').value;
var reppassword = document.getElementById('passwordrep').value;
document.getElementById('reg-form').addEventListener('submit', function(e) {
e.preventDefault();
if (password == reppassword) {
console.log("Passwords match. Submitting...");
auth.createUserWithEmailAndPassword(email, password).then(userCredential => {
console.log('Signed up!');
});
}
});
}
but all vars created at the start of the js return all null. Any ideas?
You're retrieving the values on pageload, not on submit; they'll always be empty (not null, but the empty string). Change to:
document.getElementById('reg-form').addEventListener('submit', function(e) {
e.preventDefault();
var email = document.getElementById('email').value;
var password = document.getElementById('password').value;
var reppassword = document.getElementById('passwordrep').value;
if (password == reppassword) {
console.log("Passwords match. Submitting...");
auth.createUserWithEmailAndPassword(email, password).then(userCredential => {
console.log('Signed up!');
});
}
});
I have a registration form and I want to validate that the password and email fields by adding confirm fields for each. Both field must be validated before clicking on the submit button. Is there a way to validate both email and password fields on the same form. Below is what i have for my password fields which works great but i need help to validate the email section too on the same form. thanks in advance
<Form>
<input type="email" name="email" id="email" placeholder="Email" required />
<input type="email" name="confirm_email" id="confirm_email" placeholder="Confirm Email" required />
<input type="text" name="username" id="username" placeholder="Company name" required />
<input name="password" id="password" type="password" placeholder="Password" onkeyup='check();' />
<input type="password" name="confirm_password" id="confirm_password" placeholder="Confirm Password" onkeyup='check();' />
<span id='message'></span>
</Form>
<script>
var check = function() {
if (document.getElementById('password').value ==
document.getElementById('confirm_password').value) {
document.getElementById('message').style.color = 'green';
document.getElementById('message').innerHTML = 'Password match confirmed';
} else {
document.getElementById('message').style.color = 'red';
document.getElementById('message').innerHTML = 'Please confirm your password.';
}
}</script>
You need to check for the attributes using getAttribute() on where which input is being typed in and then from their you can do the validation of your email first.
Also, to make sure that email is always getting confirmed first we need to set a global variable which is initially false but as soon the email is confirmed it becomes true and then you can move on to the password feilds.
If you directly goes towards the password the input you will see the message that please verify you email first.
Lastly, i have cleaned up your and is simplified the code as well by declaring the inputs as variable so that we can use them again in our code if needed. I have also added when input field must not be empty when doing the validation of fields.
Live Working Demo:
var emailConfirmed = false
var message = document.getElementById('message')
var email = document.getElementById('email')
var confEmail = document.getElementById('confirm_email')
var password = document.getElementById('password')
var confPassword = document.getElementById('confirm_password')
function check(e) {
if (e.getAttribute('id') == 'email' || e.getAttribute('id') == 'confirm_email') {
if (email.value != '' && confEmail.value != '' && email.value == confEmail.value) {
message.style.color = 'green';
message.innerHTML = 'Email match confirmed';
emailConfirmed = true
} else {
message.style.color = 'red';
message.innerHTML = 'Please confirm your email.';
emailConfirmed = false
}
}
if (e.getAttribute('id') == 'password' || e.getAttribute('id') == 'confirm_password') {
if (emailConfirmed) {
if (password.value != '' && confPassword.value != '' && password.value == confPassword.value) {
message.style.color = 'green';
message.innerHTML = 'Password match confirmed';
} else {
message.style.color = 'red';
message.innerHTML = 'Please confirm your password.';
}
} else {
message.style.color = 'red';
message.innerHTML = 'Please confirm your email first.'
}
}
}
input {
display: block;
}
<form>
<input type="email" name="email" id="email" placeholder="Email" onkeyup='check(this);' required />
<input type="email" name="confirm_email" id="confirm_email" placeholder="Confirm Email" onkeyup='check(this);' required />
<input name="password" id="password" type="password" placeholder="Password" onkeyup='check(this);' />
<input type="password" name="confirm_password" id="confirm_password" placeholder="Confirm Password" onkeyup='check(this);' />
<br>
<span id='message'></span>
</form>
I'm trying to build an array in javascript from user input on my HTML form. It seems the array is building fine until it gets to the .push, I then get an error
employeeid undefined
, even though I know it's being populated and I can see this when I run debug mode.
HTML
<div class="wel" align="left">
<form class="form-signin">
<p>
<input type="text" class="form-control" id="EmployeeID" name="EmployeeID" placeholder="EmployeeID" required="" autofocus="" />
</p>
<p>
<input type="text" class="form-control" id="fullname" name="fullname" placeholder="FullName" required="" autofocus="" />
</p>
<p>
<input type="text" class="form-control" id="username" name="username" placeholder="UserName" required="" autofocus="" />
</p>
<p>
<input type="email" class="form-control" id="Email" name="Email" placeholder="Email" required="" autofocus="" />
</p>
<p>
<input type="password" class="form-control" id="Password" name="Password" placeholder="password" required="" autofocus="" />
</p>
<p>
<input type="password" class="form-control" id="Password1" name="ConfirmPassword" placeholder="password" required="" autofocus="" />
</p>
<a id='subButton' class="btn btn-primary btn-lg" style="vertical-align: bottom">submit</a>
</form>
</div
javascript
$(document)
.ready(function() {
var arrayDetails = new Array();
var holdingArray = new Array();
function newEntry(employeeId, fullname, username, email, password) {
this.employeeId = employeeId;
this.fullname = fullname;
this.username = username;
this.email = email;
this.Password = password;
}
$("#subButton")
.click(function () {
debugger;
var success = true;
var password = document.getElementById("Password");
var password1 = document.getElementById("Password1");
if (password.value !== password1.value)
{
alert("Password do not match");
}
else
{
var employeeIdEntered = document.getElementById("EmployeeID").value;
if (employeeIdEntered === "") {
success = false;
}
var fullnameentered = document.getElementById("fullname").value;
if (fullnameentered === "") {
success = false;
}
var usernameEntered = document.getElementById("username").value;
if (usernameEntered === "") {
success = false;
}
var emailEntered = document.getElementById("Email").value;
if (emailEntered === "") {
success = false;
}
var passwordEnterned = document.getElementById("Password").value;
if (passwordEnterned === "") {
success = false;
}
var entry = newEntry(employeeIdEntered,
fullnameentered,
usernameEntered,
emailEntered,
passwordEnterned);
arrayDetails.push(entry);
};
if (success)
{
sendToController();
} else
{
alert("");
}
});
Your newEntry() function is missing a return statement. Don't add the attributes to this, do instead a
function newEntry(employeeId, fullname, username, email, password) {
var res = {};
res.employeeId = employeeId;
res.fullname = fullname;
res.username = username;
res.email = email;
res.Password = password;
return res;
}