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>
I have this form that the functionality is when all the required fields are completed to enable the submit button.
It was working until i added more interaction for a map gallery.
What could be wrong?
Im open to any suggestion or advice.
Im pretty new
Html
<h1>Contact me</h1>
<form action="" id="ContactForm" onsubmit="sConsole(event)">
<fieldset>
<p><label for="fullname">First Name:</label></p>
<input type="text" id="fullname" name="fullname" required />
<p><label for="lastname">Last Name:</label></p>
<input type="text" id="lastname" name="lastname" >
<p><label for="email">Email:</label></p>
<input type="email"id="email" email="email" required />
<p>Comment</p>
<label>
<textarea name="comments" id="comments" cols="30" rows="30" placeholder="Insert your comments here..." required ></textarea>
</label>
<p>Date of birth</p>
<label for="mydate">Pick a date:</label>
<input type="date" id="date" required />
<input type="submit" id="SubmitButton" disabled = "disabled" value="submit" onClick="sConsole()">
</fieldset>
Javascript
ContactForm.addEventListener("input" , () => {
if (fullname.value.length > 0 &&
lastname.value.length > 0 &&
email.value.length > 0 &&
comments.value.length > 0 &&
date.value.length > 0) {
SubmitButton.removeAttribute("disabled");
} else {
SubmitButton.setAttribute("disabled","disabled");
}
});
The new things that i added
const prevBtn = document.querySelector(".prev");
const nextBtn = document.querySelector(".next");
const mapGallery = document.querySelectorAll(".maps-gallery");
let currentlySelected = 0;
prevBtn.addEventListener("click",function(){
mapGallery[currentlySelected].classList.remove("active");
currentlySelected--;
mapGallery[currentlySelected].classList.add("active");
nextBtn.disabled = false
if (currentlySelected === 0){
prevBtn.disabled = true;
}
});
nextBtn.addEventListener("click",function(){
mapGallery[currentlySelected].classList.remove("active");
currentlySelected++;
mapGallery[currentlySelected].classList.add("active");
prevBtn.disabled = false
if (mapGallery.length === currentlySelected +1 ){
nextBtn.disabled = true;
}
});
You need to use
document.getElementById("ContactForm").addEventListener
in the code. In this case, JavaScript needs to know the ID of the element to access.
I have an HTML form with three mandatory fields in. I don't want the form to submit the AJAX call if they are empty.
$("#contact").submit(function(e){
e.preventDefault();
var ajaxurl = '<?php echo WEB_URL; ?>contact_send.php';
var data = $(this).serializeArray();
console.log(data);
var valid = true;
if( $('input[name="Name"]').val() == '' || $('input[name="Email"]').val() == '' || $('input[name="Phone"]').val() == '') {
valid = false;
}
if(valid) {
$.post(ajaxurl, data, function (response) {
$(".show_homecontact_form_success").fadeIn(1000);
$("#contact")[0].reset();
});
} else {
alert('Please fill in all mandatory fields.');
}
});
<form id="contact" name="contact" method="post" action="">
<label for="Name">Name: *</label>
<input type="text" name="Name" id="name" />
<input name="robotest" type="hidden" value="" />
<label for="Position">Position:</label>
<input type="text" name="Position" id="position" />
<label for="Company">Company:</label>
<input type="text" name="Company" id="company" />
<label for="Address">Address:</label>
<input type="text" name="Address" id="address" />
<label for="Email">Email: *</label>
<input type="text" name="Email" id="email" />
<label for="Email">Phone number: *</label>
<input type="text" name="Phone" id="phone" />
<label for="Event_Subject">What is the subject of the event?:</label>
<input type="text" name="Event_Subject" id="subject" />
<label for="Event_Date">What is the date of the event?:</label>
<input type="text" name="Event_Date" id="date" />
<label for="Additional_info">Additional Information:</label>
<br />
<textarea name="Additional_info" rows="20" cols="20" id="info"></textarea>
<input id="formsubmitted" type="submit" name="submit" value="submit" class="submit-button" />
</form>
This does give the popup box if you try and fill it in empty, but I have received an email with all blank fields.
How is the user getting past the validation and managing to send the form through blank?
More than likely you've not popped in a preventDefault() in there, so the form is doing a normal (non-AJAX) post after your function ends. What's the method/action on your form? Perhaps there doesn't need to be an action at all?
Try this:
$("#contact").submit(function(e){
e.preventDefault();
var ajaxurl = '<?php echo WEB_URL; ?>contact_send.php';
var data = $(this).serializeArray();
console.log(data);
var valid;
if( $('input[name="Name"]').val().length > 0
&& $('input[name="Email"]').val().length > 0
&& $('input[name="Phone"]').val().length > 0) {
valid = true;
} else {
valid = false;
}
if(valid) {
$.post(ajaxurl, data, function (response) {
$(".show_homecontact_form_success").fadeIn(1000);
$("#contact")[0].reset();
});
} else {
alert('Please fill in all mandatory fields.');
}
});
As Jigar pointed out, you can shorten the code by assigning an initial value to the valid variable and removing else block:
var valid = false;
if( $('input[name="Name"]').val().length > 0
&& $('input[name="Email"]').val().length > 0
&& $('input[name="Phone"]').val().length > 0) {
valid = true;
}
When I run my javascript code in html it's fine, but when I run the same code on localhost it shows me this message in the console:
Uncaught TypeError: Cannot read property 'style' of null
This is my code
<form method="post">
<ul id="edit">
<li>
<input type="text" name="adress" id="adress" placeholder="Adresa" />
</li>
<li>
<input type="text" name="city" id="city" placeholder="Grad" />
</li>
<li>
<input type="number" name="zip" id="zip" placeholder="Poštanski broj" />
</li>
<li>
<input type="tel" name="phone_number" id="phone_number" placeholder="Tel. broj" />
</li>
<li>
<input type="password" name="password" id="password" placeholder="Lozinka" />
<div class="password_strength" id="password_strength"></div>
</li>
<li>
<input type="password" name="repassword" id="repassword" placeholder="Ponoviti lozinku" onkeyup="checkPass(); return false;" />
</li><div id="confirmMessage"></div>
<br>
<li>
<input type="submit" name="submit" id="submit" value="Izmjeni" />
</li>
<br>
</ul>
</form>
<script>
function checkPass() {
var password = document.getElementById('password');
var repassword = document.getElementById('repassword');
var message = document.getElementById('confirmMessage');
var goodColor = "#66cc66";
var badColor = "#ff6666";
if (password.value == repassword.value) {
repassword.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "Passwords Match!"
} else {
repassword.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = "Passwords Do Not Match!";
}
}
$('#password, #username').keydown(function (e) {
if (e.which == 32) {
return false;
}
});
$('#password').keyup(function () {
var PasswordLength = $(this).val().length;
var PasswordStrength = $('#password_strength');
if (PasswordLength <= 0) {
PasswordStrength.html('');
PasswordStrength.removeClass('normal weak strong verystrong');
}
if (PasswordLength > 0 && PasswordLength < 4) {
PasswordStrength.html('weak');
PasswordStrength.removeClass('normal strong verystrong').addClass('weak');
}
if (PasswordLength > 4 && PasswordLength < 8) {
PasswordStrength.html('Normal');
PasswordStrength.removeClass('weak strong verystrong').addClass('normal');
}
if (PasswordLength >= 8 && PasswordLength < 12) {
PasswordStrength.html('Strong');
PasswordStrength.removeClass('weak normal verystrong').addClass('strong');
}
if (PasswordLength >= 12) {
PasswordStrength.html('Very Strong');
PasswordStrength.removeClass('weak normal strong').addClass('verystrong');
}
});
</script>
First part of the code should add color to my input box for repeaedt password in green if password match or red if they don't, but it is always red.
Second part should add a class for password strength, but nothing.
First you should have a line number associated with your error code if you used the console. Second I noticed that there is a line that ends with no semi-colon
message.innerHTML = "Passwords Match!"
which is not an automatic error, but you want to eliminate possible misinterpretation by your browser.
Problem solved,
I made mistake in part of code what I didn't post in my question.
I had two same password ids.
So I had to replace:
<form action="login.php">
E-mail: <input type="mail" name="mail" id="mail"/><br><br>
Lozinka: <input type="password" name="login_password" id="login_password"/><br><br>
<input type="submit" value="Prijavi se"/><br><br>
Zaboravljena lozinka?
</form>
With:
<form action="login.php">
E-mail: <input type="mail" name="mail" id="mail"/><br><br>
Lozinka: <input type="password" name="login_password" id="login_password"/><br><br>
<input type="submit" value="Prijavi se"/><br><br>
Zaboravljena lozinka?
</form>
Thank you all for help :)
I am trying to create a "contact us" forum with html.
This is my current html:
<form id="contact_form" name="contact_form" method="post" action="validate()">
<div class="row">
<label for="name" class="desc" style="font-size: 30px;">Your name:</label><br />
<input id="name" class="input" name="name" type="text" value="" size="50" /><br />
</div><br /><br />
<div class="row">
<label for="email" class="desc" style="font-size: 30px;">Your email:</label><br />
<input id="email" class="input" name="email" type="text" value="" size="50" /><br />
</div><br /><br />
<div class="row">
<label for="message" class="desc" style="font-size: 30px;">Your message:</label><br />
<textarea id="message" class="input" name="message" rows="8" cols="50"></textarea><br />
</div>
<div class="row"><br />
<input id="submit_button" type="submit" value="Send email"/>
</div>
</form>
And my javascript:
function validate() {
//Make sure name is filled out
var x = document.forms["contact_form"]["name"].value;
if (x == null || x == "") {
alert("Name must be filled out");
return false;
}
//Make sure email is filled out
var x = document.forms["contact_form"]["email"].value;
if (x == null || x == "") {
alert("Email must be filled out");
return false;
}
//Make sure message is filled out
var x = document.forms["contact_form"]["message"].value;
if (x == null || x == "") {
alert("Message must be filled out");
return false;
}
//Validate email
var x = document.forms["contact_form"]["email"].value;
var atpos = x.indexOf("#");
var dotpos = x.lastIndexOf(".");
if (atpos< 1 || dotpos<atpos+2 || dotpos+2>=x.length) {
alert("Not a valid email");
return false;
}
}
For some reason when I hit "submit" it takes me to a page called "validate()" How can I make it so that when I click submit it EXECUTES the function validate(), not just take me to a page called validate()...
NOTE: Nevermind the php, right now focus on the html and javascript
It redirects it to that page because you are setting the action to go there. That does not execute JavaScript. You are looking for onsubmit.
Change action="validate()" to onsubmit="return validate();"
And as always, it would be better to set it unobtrusively instead of inline.