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!');
});
}
});
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>
I have a problem. When I clicked the submit button nothing happens, even when I filled out the username and password with numbers (I don't want the username and password contains any number so I did make the condition for it), there is no alert display. I do not know where the problem comes from? Can you guys help me with this
Note: the reset function works fine
function validateInput() {
var firstName = document.forms["sign_up"]["firstName"];
var lastName = document.forms["sign_up"]["lastName"];
var email = document.forms["sign_up"]["email"];
var reg = /^[a-zA-Z]+$/;
if (firstName.value !== '' || lastName.value !== '' || email.value !== '') {
if (firstName.value.match(reg) && lastName.value.match(reg)) {
alert("Form is submitted");
// return true;
return false; // for the demo, so it doesn't submit
} else {
if (firstName.value.match(reg) === false) {
document.getElementById("error").innerHTML = "Numbers are not allowed in username";
return false;
} else if (lastName.value.match(reg) === false) {
document.getElementById("error").innerHTML = "Numbers are not allowed in password";
return false;
}
}
}
}
function reset() {
document.getElementById("first").innerHTML = "";
document.getElementById("last").innerHTML = "";
document.getElementById("email").innerHTML = "";
}
<form id="sign_up" onsubmit="return validateInput()">
<p id="error"></p>
<label for="firstName">First Name</label>
<input type="text" id="firstName" value="" placeholder="Enter your first name">
<label for="lastName">Last Name</label>
<input type="text" id="lastName" value="" placeholder="Enter your last name">
<label for="email">Email</label>
<input type="email" id="email" value="" placeholder="Enter your email">
<button type="submit">Submit</button>
<button type="button" onclick="reset();">Cancel</button>
</form>
Use the Pattern attribute in input for validation like below
<input type="text" id="firstName" value="" pattern="[^0-9]*" title="Numbers are not allowed" placeholder="Enter your first name">
for more references: https://www.w3schools.com/tags/att_input_pattern.asp
And for reset functionality use reset
<input type="reset" value="reset">
It's better than create a special function for it and it saves your number of lines:-)
First, try to avoid to inline event handlers as they are not rec-emended at all. Also to reset form values you can simply use reset() method on the form.
Also, do not use innerHTML just to set the text of your error. You can use textContent instead which is better fit in your example.
You can use addEventListener with submit event to check for validation on your firstname and lastname.
I have fixed your code and its all working as expected.
Live Working Demo:
let form = document.getElementById("sign_up")
var firstName = document.getElementById("firstName")
var lastName = document.getElementById("lastName")
var email = document.getElementById("email")
var reset = document.getElementById("clearValues")
var reg = /^[a-zA-Z]+$/;
form.addEventListener('submit', function(e) {
e.preventDefault()
if (firstName.value != '' || lastName.value != '' || email.value != '') {
if (firstName.value.match(reg) && lastName.value.match(reg)) {
alert("Form is submitted");
} else if (!firstName.value.match(reg)) {
document.getElementById("error").textContent = "Numbers are not allowed in username";
} else if (!lastName.value.match(reg)) {
document.getElementById("error").textContent = "Numbers are not allowed in password";
}
}
})
reset.addEventListener('click', function(e) {
document.getElementById("sign_up").reset();
})
input {
display:block;
}
<head>
</head>
<body>
<form id="sign_up" action="#">
<p id="error"></p>
<label for="firstName">First Name</label>
<input type="text" id="firstName" value="" placeholder="Enter your first name">
<label for="lastName">Last Name</label>
<input type="text" id="lastName" value="" placeholder="Enter your last name">
<label for="email">Email</label>
<input type="email" id="email" value="" placeholder="Enter your email">
<button type="submit">
Submit
</button>
<button type="button" id="clearValues" onclick="reset();">
Cancel
</button>
</form>
</body>
You don't need to return a function in onsubmit event. This should work fine.
<form id="sign_up" onsubmit="validateInput()">
Reference:
https://www.w3schools.com/jsref/event_onsubmit.asp
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>
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");