I want to create a sign-up form. I have 6 inputs: First Name, Last Name, E-mail, Password, Password confirmation and a checkbox for user agreement. If inputs have class="valid", value is valid, otherwise invalid. I put all the classes a default class="invalid". I want to disable my submit button until all input fields have class="valid". According to my research, I saw that the button should be disabled first using the window.onload eventlistener, but I still couldn't figure out how to do it.
This is the basic form:
<form class="signup__form" action="/">
<input class="invalid" type="text" name="fname" placeholder="name"/> </br>
<input class="invalid" type="text" name='lname' placeholder="Last Name" /></br>
<input class="invalid" type="email" name='email' placeholder="E-mail" /></br>
<input class="invalid" type="password" name="password" placeholder="Password" />
<input class="invalid" type="password" name="password" placeholder="Password Confirm" />
<input class="invalid" type="checkbox" /> User Agreement</br>
<button type="submit" >Sign Up</button>
</form>
I am controlling checkbox validation with an eventlistener:
checkbox.addEventListener('click', (e) => {
if (e.target.checked) {
checkbox.classList.remove('invalid');
checkbox.classList.add('valid');
} else {
checkbox.classList.remove('valid');
checkbox.classList.add('invalid');
}
})
And for the rest, i am checking with regexs:
// Regex values
const regexs = {
fname: /^[a-zA-Z0-9]{3,24}$/,
lname: /^[a-zA-Z0-9]{3,24}$/,
email: /^([a-z\d\.-]+)#([a-z\d-]+)\.([a-z]{2,8})$/,
password: /^[\w#-]{8,20}$/
};
// Regex Validation
const validation = (input, regex) => {
if (regex.test(input.value)) {
input.classList.remove('invalid');
input.classList.add('valid');
} else {
input.classList.remove('valid');
input.classList.add('invalid');
}
}
inputs.forEach((input) => {
input.addEventListener('keyup', (e) => {
validation(e.target,regexs[e.target.attributes.name.value])
})
})
Something like this might come in handy.
var form = document.querySelector('.signup__form'), is_valid = false, fields, button;
form.addEventListener('change', function(){
fields = form.querySelectorAll('input');
button = form.querySelector('button');
for (var i = fields.length - 1; i >= 0; i--) {
if( fields[i].classList.contains('invalid') )
{
is_valid = false;
break;
}
is_valid = true;
}
is_valid ? button.removeAttribute('disabled'): button.setAttribute('disabled', 'disabled');
});
<form class="signup__form" action="/">
<input class="invalid" type="text" name="fname" placeholder="name"/> <br>
<input class="invalid" type="text" name='lname' placeholder="Last Name" /><br>
<input class="invalid" type="email" name='email' placeholder="E-mail" /><br>
<input class="invalid" type="password" name="password" placeholder="Password" />
<input class="invalid" type="password" name="password" placeholder="Password Confirm" />
<input class="invalid" type="checkbox" /> User Agreement<br>
<button type="submit" disabled>Sign Up</button>
</form>
Since you don't have all of your code, I'm adding a second example myself so that I can fully test the validation part.
But you just need to copy the above JavaScript code and set the button to disabled="disabled"in the first place.
var form = document.querySelector('.signup__form'),
is_valid = false,
fields, button;
form.addEventListener('change', function() {
fields = form.querySelectorAll('input');
button = form.querySelector('button');
for (var i = fields.length - 1; i >= 0; i--) {
if (fields[i].value.length) {
fields[i].classList.remove('invalid');
} else {
fields[i].classList.add('invalid');
}
if (fields[i].classList.contains('invalid')) {
is_valid = false;
break;
}
is_valid = true;
}
is_valid ? button.removeAttribute('disabled') : button.setAttribute('disabled', 'disabled');
});
<form class="signup__form" action="/">
<input class="invalid" type="text" name="fname" placeholder="name" /> <br>
<input class="invalid" type="text" name='lname' placeholder="Last Name" /><br>
<input class="invalid" type="email" name='email' placeholder="E-mail" /><br>
<input class="invalid" type="password" name="password" placeholder="Password" />
<input class="invalid" type="password" name="password" placeholder="Password Confirm" />
<input class="invalid" type="checkbox" /> User Agreement<br>
<button type="submit" disabled>Sign Up</button>
</form>
Note: This example does not follow because it does not validate the Checkbox.
#Enes, 1. kod parçacığındaki JavaScript kodunu kopyalarsan çalışacaktır. 2. Kodu test edebilmen için ekledim. Bir değer girilmişse onu doğru "valid" kabul eder.
I would try to the native use of HTML properties (pattern & required) and CSS instead of giving in to javascript. Just give it a go, and see how it feels like. Do note that I excluded a pattern on your email input.
The only thing I would use javascript for is to check if the password fields are the same, but I would do that by injecting the password of the first password input into the confirming password input's pattern attribute, replacing ^[\w#-]{8,20}$.
The pink background is just there to show-case the validation rules.
By the way, you got the wrong formatting on some of the HTML tags. You don't need an ending slash on input and you should type <br/>, not </br>.
input:invalid {
background-color: pink;
}
form:invalid button[type="submit"] {
opacity: 0.5;
}
<form class="signup__form" action="/">
<input type="text" required pattern="^[a-zA-Z0-9]{3,24}$" placeholder="Name"> <br/>
<input type="text" required pattern="^[a-zA-Z0-9]{3,24}$" placeholder="Last Name"><br/>
<input type="email" required placeholder="E-mail"><br/>
<input type="password" required pattern="^[\w#-]{8,20}$" placeholder="Password"><br/>
<input type="password" required pattern="^[\w#-]{8,20}$" placeholder="Password Confirm"><br/>
<input type="checkbox" required>User Agreement<br/>
<button type="submit" >Sign Up</button>
</form>
you can use required="required", then the submit won't be called before the field has value.
A solution which tests the number of invalid classes:
var checkbox = document.querySelector("input[type=checkbox]");
var inputs = document.querySelectorAll("input:not([type='checkbox'])");
var but = document.querySelector("button[type=submit]");
but.disabled= true;
checkbox.addEventListener('click', (e) => {
if (e.target.checked) {
checkbox.classList.remove('invalid');
checkbox.classList.add('valid');
} else {
checkbox.classList.remove('valid');
checkbox.classList.add('invalid');
}
but.disabled = !document.querySelectorAll("input.invalid").length == 0;
})
// Regex values
const regexs = {
fname: /^[a-zA-Z0-9]{3,24}$/,
lname: /^[a-zA-Z0-9]{3,24}$/,
email: /^([a-z\d\.-]+)#([a-z\d-]+)\.([a-z]{2,8})$/,
password: /^[\w#-]{8,20}$/
};
// Regex Validation
const validation = (input, regex) => {
if (regex.test(input.value)) {
input.classList.remove('invalid');
input.classList.add('valid');
} else {
input.classList.remove('valid');
input.classList.add('invalid');
}
}
inputs.forEach((input) => {
input.addEventListener('keyup', (e) => {
validation(e.target,regexs[e.target.attributes.name.value]);
but.disabled = !document.querySelectorAll("input.invalid").length == 0;
})
})
<form class="signup__form" action="/">
<input class="invalid" type="text" name="fname" placeholder="name"/> </br>
<input class="invalid" type="text" name='lname' placeholder="Last Name" /></br>
<input class="invalid" type="email" name='email' placeholder="E-mail" /></br>
<input class="invalid" type="password" name="password" placeholder="Password" />
<input class="invalid" type="password" name="password" placeholder="Password Confirm" />
<input class="invalid" type="checkbox" /> User Agreement</br>
<button type="submit" >Sign Up</button>
</form>
We will use couple of properties to validate the form which are required, pattern, disabled and also we will use CSS properties to control the form validation
input:invalid {
background-color: red;
}
form:invalid input[type="submit"] {
opacity: 0.5;
cursor: not-allowed;
}
<form class="login__form" action="/">
<input type="email" required placeholder="E-mail"><br/><br/>
<input type="password" required pattern="^[\w#-]{8,20}$" placeholder="Password"><br/><br/>
<input type="submit" >
</form>
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 have this javascript below:
<script type="text/javascript">
function PassCheck() {
var password = document.getElementById('password');
var vpassword = document.getElementById('vpassword');
if(password.value!= vpassword.value){
document.getElementById("button1").disabled = true;
}
}
</script>
HTML code:
Password: <input type="password" name="password" id="password" required onchange='PassCheck();'/> <br>
Verify Password: <input type="password" name="vpassword" required id="vpassword" onchange='PassCheck();'/> <br>
<input type="submit" value="Submit" id="button1" name="submit" onchange='PassCheck();'/>
The submit button is disabled only the first time and the disbale button doesn't work after second attempt. I am not sure why its not working. Please help! Thanks in advance.
You simply need to add an else condition that re-enables your button once the values match:
function PassCheck() {
var password = document.getElementById('password');
var vpassword = document.getElementById('vpassword');
if (password.value != vpassword.value) {
document.getElementById("button1").disabled = true;
}
else {
document.getElementById("button1").disabled = false;
}
}
Password: <input type="password" name="password" id="password" required onchange='PassCheck();' /> <br>
Verify Password: <input type="password" name="vpassword" required id="vpassword" onchange='PassCheck();' /> <br>
<input type="submit" value="Submit" id="button1" name="submit" onchange='PassCheck();' />
onchange occurs only when the element loses focus, so try to use onkeyup or oninput events. Also don't forget to set disabled to false.
function PassCheck() {
var password = document.getElementById('password');
var vpassword = document.getElementById('vpassword');
document.getElementById("button1").disabled = password.value.length === 0 ||
password.value != vpassword.value;
}
PassCheck();
Password: <input type="password" name="password" id="password" required onkeyup='PassCheck();'/> <br>
Verify Password: <input type="password" name="vpassword" required id="vpassword" onkeyup='PassCheck();'/> <br>
<input type="submit" value="Submit" id="button1" name="submit"/>
I have a JavaScript login validation block, however my if block is partially working, i.e condition after the AND(&&) is not being checked resulting not applying validation on password, here is my code snippet.
function validateLogin(){
var userid = document.getElementById('user_id');
var passid = document.getElementById('pass_id');
if((userid.value.length < 3) && (passid.value.length < 6)) {
document.getElementById('user_error').setAttribute("style","color:red")
document.getElementById('user_error').innerHTML="invalid username/password.";
return false;
}
return true;
}
<form id="login_form" name="login" onsubmit=" return validateLogin()" >
<div>
<input class="user_login_form" id='user_id' type="text" required tabindex="1" name="user_id" autofocus autocomplete=off placeholder ="User Name">
</div>
<div>
<input class="user_login_form" id='pass_id' required type="password" tabindex="2" name="user_pass" placeholder ="Password">
<p id ="user_error"></p>
</div>
<input class="user_login_submit" type="submit" id='btnLogin' tabindex="3" name="login_btnSubmit" value="LOGIN" >
It's optimization of if. If first part is false, then further comparisons are not executed because of false && Anything results in false
You need to compare using OR
function validateLogin() {
var userid = document.getElementById('user_id');
var passid = document.getElementById('pass_id');
if ((userid.value.length < 3) || (passid.value.length < 6)) {
document.getElementById('user_error').setAttribute("style", "color:red")
document.getElementById('user_error').innerHTML = "invalid username/password.";
return false;
}
return true;
}
<form id="login_form" name="login" onsubmit=" return validateLogin()">
<div>
<input class="user_login_form" id='user_id' type="text" required tabindex="1" name="user_id" autofocus autocomplete=off placeholder="User Name">
</div>
<div>
<input class="user_login_form" id='pass_id' required type="password" tabindex="2" name="user_pass" placeholder="Password">
<p id="user_error"></p>
</div>
<input class="user_login_submit" type="submit" id='btnLogin' tabindex="3" name="login_btnSubmit" value="LOGIN">
You want to use OR here. So your throw your error if userid length is less than 3 OR passid length is less than 6.
if((userid.value.length < 3) || (passid.value.length < 6))
I'm attempting to build an object of the input values in the form below, then log that object to the console; but it the values are not being retrieved properly.
What is wrong with my code?
document.getElementById('myForm').addEventListener('submit', contactPerson);
function contactPerson(e) {
var personName = document.getElementsByClassName('personName').value;
var personEmail = document.getElementsByClassName('personEmail').value;
var personMessage = document.getElementsByClassName('personMessage').value;
var contact = {
name: personName,
email: personEmail,
message: personMessage
}
console.log(contact);
e.preventDefault();
}
<form id="myForm">
<label for="inputHorizontalSuccess">Name</label>
<input type="text" class="form-control form-control-success" id="inputHorizontalSuccess" class="personName" placeholder="Name"><br>
<label for="inputHorizontalSuccess">Email</label>
<input type="email" class="form-control form-control-success" id="inputHorizontalSuccess" class="personEmail" placeholder="name#example.com"><br>
<label for="inputHorizontalSuccess">Message</label>
<input type="text" class="form-control form-control-success" id="inputHorizontalSuccess" class="personMessage" placeholder="Your Message"><br>
<button type="submit">Submit</button>
</form>
You have multiple Ids:
<input type="text" class="form-control form-control-success" id="inputHorizontalSuccess" id="personName" placeholder="Name">
You can either remove inputHorizontalSuccess.
Or add a name and get value from it instead, incase you must have inputHorizontalSuccess.
This should do it:
<input type="text" class="form-control form-control-success" id="inputHorizontalSuccess1" name="personName" placeholder="Name">
<input type="email" class="form-control form-control-success" id="inputHorizontalSuccess2" name="personEmail" placeholder="name#example.com">
<input type="text" class="form-control form-control-success" id="inputHorizontalSuccess3" name="personMessage" placeholder="Your Message">
var personName = document.querySelector('[name="personName"]').value;
var personEmail = document.querySelector('[name="personEmail"]').value;
var personMessage = document.querySelector('[name="personMessage"]').value;
I recommend you read this question on how to get value from the DOM.
How do I get the value of text input field using JavaScript?
Only the first class attribute in an element definition is applied. This means that when you write the following:
<input type="text" class="form-control form-control-success" ... class="personName" placeholder="Name">
The later "class" attribute will not apply. This means that the element cannot be selected by this class.
Document.getElementsByClassName returns a live HTMLCollection even if there is only a single element. This means that when you write:
var personName = document.getElementsByClassName('personName').value;
There is no value property in the live HTMLCollection returned by the call to Document.getElementsByClassName, so it will return undefined.
document.getElementById('myForm').addEventListener('submit', contactPerson);
function contactPerson(e) {
var personName = document.getElementsByClassName('personName')[0].value;
var personEmail = document.getElementsByClassName('personEmail')[0].value;
var personMessage = document.getElementsByClassName('personMessage')[0].value;
var contact = {
name: personName,
email: personEmail,
message: personMessage
}
console.log(contact);
e.preventDefault();
}
<form id="myForm">
<label for="inputHorizontalSuccess">Name</label>
<input type="text" class="form-control form-control-success personName" id="inputHorizontalSuccess" placeholder="Name"><br>
<label for="inputHorizontalSuccess">Email</label>
<input type="email" class="form-control form-control-success personEmail" id="inputHorizontalSuccess" placeholder="name#example.com"><br>
<label for="inputHorizontalSuccess">Message</label>
<input type="text" class="form-control form-control-success personMessage" id="inputHorizontalSuccess" placeholder="Your Message"><br>
<button type="submit">Submit</button>
</form>
However, you should probably use ID's instead of classes and Element#querySelector, to avoid conflict:
document.getElementById('myForm').addEventListener('submit', contactPerson);
function contactPerson(e) {
var personName = document.querySelector('#personName').value;
var personEmail = document.querySelector('#personEmail').value;
var personMessage = document.querySelector('#personMessage').value;
var contact = {
name: personName,
email: personEmail,
message: personMessage
}
console.log(contact);
e.preventDefault();
}
<form id="myForm">
<label for="inputHorizontalSuccess">Name</label>
<input type="text" class="form-control form-control-success" id="personName" placeholder="Name"><br>
<label for="inputHorizontalSuccess">Email</label>
<input type="email" class="form-control form-control-success" id="personEmail" placeholder="name#example.com"><br>
<label for="inputHorizontalSuccess">Message</label>
<input type="text" class="form-control form-control-success" id="personMessage" placeholder="Your Message"><br>
<button type="submit">Submit</button>
</form>
This is my first time with javascript. I'm making a basic login page where there is a control for the email input. I would like to put an error message of some kind when someone gives an email address with illegal symbol. Here my code:
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
<meta charset="UTF-8">
</head>
<body>
<div>
<form action="Home.html" method="post">
<label for="id">Username</label>
<input type="text" name="id" id="id" value="" />
<br/>
<label for="pass">Password</label>
<input type="password" name="pass" id="pass" value="" />
<br/>
<label for="email">Email</label>
<input type="email" name="email" id="email" value="" />
<br/>
<script type="text/javascript">
function checkEmail ()
{
var emailObject = document.getElementById("email");
var email = emailObject.getAttribute("value").toString();
var error = document.createTextNode("Uncorrect email");
var result = email.search("/[^(a-z | A-Z | 0-9 | #)]/");
if(result !== -1)
{
emailObject.appendChild(error);
}
}
</script>
<button type="button" onclick="checkEmail()"> Confirm </button>
</form>
</div>
</body>
</html>
I have a function I use to validate email addresses, it uses regex. I would suggest jQuery just to show/hide the error message.
function validEmail(val){
if(val.length < 6 || val.length > 255) return false;
return new RegExp(/^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/).test(val);
}
$(function(){
$("#email").on("change", function(){
var email = $("#email").val();
if(!validEmail(email)){
$("#emailError").show();
} else {
$("#emailError").hide();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<!-- Some Inputs here -->
<span id='emailError' style='display: none;'>Please enter a valid email address</span><br>
<input type='email' id='email' name='email' placeholder='Email Address' />
<!-- More Inputs here -->
<button type='submit'>Submit</button>
</form>
you're trying to append something to an input element (email input, in this case). I'd suggest to append it to your main div, which in this case I have identified as "YOUR_ID".
Also, I suggest you a more efficint way to check a valid email.
follow the below example
<body>
<div id="YOUR_ID">
<form action="Home.html" method="post">
<label for="id">Username</label>
<input type="text" name="id" id="id" value="" />
<br/>
<label for="pass">Password</label>
<input type="password" name="pass" id="pass" value="" />
<br/>
<label for="email">Email</label>
<input type="email" name="email" id="email" value="" />
<br/>
<script type="text/javascript">
function checkEmail ()
{
var emailObject = document.getElementById("email");
var divObject = document.getElementById("YOUR_ID");
var email = emailObject.getAttribute("value").toString();
var error = document.createTextNode("Uncorrect email");
var check = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
var result = check.test(email);
if(result !== -1)
{
divObject.appendChild(error);
}
}
</script>
<button type="button" onclick="checkEmail()"> Confirm </button>
</form>
</div>
</body>