preventDefault not preventing submit form - javascript

I have problems with my form submittiting even if the fields are not valid.
I've tried a lot of different code, but I'm currently with this.
const form = document.getElementById('kontaktskjema');
const email = document.getElementById('mail');
const emailError = document.querySelector('#mail + span.errorkontakt');
const navn = document.getElementById('navn');
const navnError = document.querySelector('#navn + span.errorkontakt');
const telefon = document.getElementById('telefon');
const telefonError = document.querySelector('#telefon + span.errorkontakt')
const message = document.getElementById('message');
const messageError = document.querySelector('#message + span.errorkontakt')
const navnboks = document.querySelector('.navnboks')
const teleboks = document.querySelector('.teleboks')
const mailboks = document.querySelector('.mailboks')
const messageboks = document.querySelector('.messageboks')
const vernboks = document.querySelector('.vernboks')
const personvern = document.getElementById('checkbox');
const personvernError = document.querySelector('#checkbox + span.errorkontakt')
const submitbtn = document.getElementById('submitbtn');
// THIS DIV WILL CONTAIN ERROR MESSAGES
const errOutput = document.querySelector('.errorsOutput')
email.addEventListener('input', function (event) {
if (email.validity.valid) {
mailboks.setAttribute("class", "data-validation-error-ok" )
emailError.innerHTML = '';
emailError.className = 'errorkontakt';
} else {
showError();
}
});
navn.addEventListener('input', function (event) {
if (navn.validity.valid) {
navnError.innerHTML = '';
navnError.className = 'errorkontakt';
navnboks.setAttribute("class", "data-validation-error-ok" )
} else {
showError();
}
})
telefon.addEventListener('input', function (event) {
if (telefon.validity.valid) {
telefonError.innerHTML = '';
telefonError.className = 'errorkontakt';
teleboks.setAttribute("class", "data-validation-error-ok" )
} else {
showError();
}
})
message.addEventListener('input', function (event) {
if (message.validity.valid) {
messageboks.setAttribute("class", "data-validation-error-ok" )
messageError.innerHTML = '';
messageError.className = 'errorkontakt';
} else {
showError();
}
})
personvern.addEventListener('change', function (event) {
if (personvern.checked == true) {
vernboks.setAttribute("class", "data-validation-error-ok" )
} else {
showError();
}
})
function makeRed() {
if (!navn.validity.valid) {
navnboks.setAttribute("class", "data-validation-error-true")
}
if (!email.validity.valid) {
mailboks.setAttribute("class", "data-validation-error-true")
}
if (!telefon.validity.valid) {
teleboks.setAttribute("class", "data-validation-error-true")
}
if (!message.validity.valid) {
messageboks.setAttribute("class", "data-validation-error-true")
}
if (!personvern.checked == true) {
vernboks.setAttribute("class", "data-validation-error-true")
}
};
function divFill() {
if (navnError.textContent != '') {
errOutput.innerHTML += '<li>Navn</li>'
}
if (emailError.textContent != '') {
errOutput.innerHTML += '<li>E-mail</li>'
}
if (telefonError.textContent != '') {
errOutput.innerHTML += '<li>Telefonnummer</li>'
}
if (messageError.textContent != '') {
errOutput.innerHTML += '<li>Beskjed</li>'
}
}
function showError() {
errOutput.innerHTML = ''
if(navn.validity.valueMissing) {
navnError.textContent = '* Du må fylle inn navnet ditt';
navnError.setAttribute("class", "data-validation-error-true" )
} else if(navn.validity.tooShort) {
navnError.textContent = '* Du må fylle inn hele navnet ditt'
}
if(email.validity.valueMissing) {
emailError.setAttribute("class", "data-validation-error-true" )
emailError.textContent = '* Vennligst fyll inn e-posten din';
} else if(email.validity.typeMismatch) {
emailError.textContent = '* Dette er ikke en gyldig e-postadresse.';
} else if(email.validity.tooShort) {
emailError.textContent = `* Email should be at least ${ email.minLength } characters; you entered ${ email.value.length }.`;
}
if(telefon.validity.valueMissing) {
telefonError.textContent = '* Du må fylle inn telefonnummeret ditt'
telefonError.setAttribute("class", "data-validation-error-true" )
} else if(telefon.validity.tooShort) {
telefonError.textContent = '* Du mangler ett eller flere tall. Vennligst dobbeltsjekk.'
}
if(message.validity.valueMissing) {
messageError.setAttribute("class", "data-validation-error-true" )
messageError.textContent = '* Beskjeden mangler, vennligst fyll inn'
} else if(message.validity.tooShort) {
messageError.textContent = `* Beskjed må være minst ${ message.minLength } tegn.`;
}
}
emailError.className = 'errorkontakt kontaktactive';
navnError.className = 'errorkontakt kontaktactive';
telefonError.className = 'errorkontakt kontaktactive';
messageError.className ='errorkontakt kontaktactive';
console.log(form)
form.addEventListener('submit', function(event) {
if (!navn.validity.valid || !email.validity.valid || !telefon.validity.valid || !message.validity.valid) {
makeRed();
divFill();
event.preventDefault();
console.log('Runs')
}})
<div id="contact-form-wrapper" class="align-right-50 lazyload">
<div id="contact-form-padding">
<h2>Send oss en melding</h2>
<p><span class="required">*</span> obligatorisk felt som du må fylle ut</p><br>
<div class="errorsOutput">
</div>
<div class="skjema">
<form id="kontaktskjema" action="nyhandler.kontakt.php" method="post" novalidate>
<input type="hidden" id="sendtfra" name="Sidetittel" value="{title}" />
<input type="hidden" id="sendtfraURL" name="Side URL" value="{url}" />
<div class="navnboks">
<p>
<label for="navn">
<span>* Navn:</span>
<input type="text" id="navn" name="navn" required minlength="3" class="input-text w100">
<span class="errorkontakt" aria-live="polite"></span>
</label>
</p>
</div>
<div class="mailboks">
<p>
<label for="mail">
<span>* E-post:</span>
<input type="email" id="mail" name="mail" required minlength="6" class="input-text w100">
<span class="errorkontakt" aria-live="polite"></span>
</label>
</p>
</div>
<div class="teleboks">
<p>
<label for="telefon">
<span>* Telefonnummer:</span>
<input type="tel" id="telefon" name="telefon" required minlength="8" class="input-text w100">
<span class="errorkontakt" aria-live="polite"></span>
</label>
</p>
</div>
<div class="messageboks">
<p>
<label for="message">
<span>* Melding:</span>
<input type="text" id="message" name="message" required minlength="10" class="input-text w100">
<span class="errorkontakt" aria-live="polite"></span>
</label>
</p>
</div>
<div class="vernboks">
<input type="hidden" id="recapta" name="g-recaptcha-response" />
<p>
<label for="personvern">
<div class="personvern">
<span>* Personvern:</span>
<br>
<input type="checkbox" id="checkbox" name="checkbox" required>
<span>Jeg har lest og godkjent Personvernserklæringen (åpnes i nytt vindu)</span>
<span class="errorkontakt" aria-live="polite"></span>
</div>
</label>
</p>
</div>
<button type="submit" value="Send" class="button-send">Send</button>
</form>
</div>
</div>
</div>
<div class="clear"></div>
</div>
I know it's weirdly specific, and i'll probably clean it up after i get it to work. Right now the validation completes, and runs the functions makeRed() and divFill(), both functions are there to help with accessability issues when not valid, but the form still submits and goes to the handler php.
Thanks.

getElementsByTagName
will return the form tag's value in [0]th location.
So you might need to change your first line of your javascript code as :
const form = document.getElementsByTagName('form')[0];
It will work .

Related

Check all input's validity first, then submit Vanilla JS

I'm working on a form page that has multiple input fields. There is some error text to show if the inputs are not valid.
After the user submits all the input fields correctly I want to show a modal. The form validation is working almost fine except for the CVC input. It's only checking when the CVC field is empty.
What can I do to fix this?
const form = document.querySelector('form');
const inputs = document.querySelectorAll('input');
const modal = document.querySelector('.modal');
const modalClose = document.querySelector('.close');
form.addEventListener('submit',(e)=>{
e.preventDefault();
inputs.forEach(input=>{
if(input.classList.contains('name-input')){
containsNameInput(input)
}else if(input.classList.contains('date')){
containsDateInput(input)
}else{
containsOtherInput(input)
}
if(input.parentElement.classList.contains('error-empty')
|| input.parentElement.classList.contains('error-invalid')
||input.parentElement.parentElement.classList.contains('error-invalid')
|| input.parentElement.parentElement.classList.contains('error-empty')){
modal.style.display = 'none';
}else{
modal.style.display = "block";
}
})
})
const containsNameInput = function(input){
if(input.value === ''){
input.parentElement.classList.add('error-empty');
input.parentElement.classList.remove('error-invalid');
}else if(input.value !== '' && input.value.match(/^[0-9]+$/) !== null){
input.parentElement.classList.remove('error-empty');
input.parentElement.classList.add('error-invalid');
}
else{
input.parentElement.classList.remove('error-empty');
input.parentElement.classList.remove('error-invalid');
}
}
const containsDateInput = function(input){
if(input.value === ''){
input.parentElement.parentElement.classList.add('error-empty');
input.parentElement.parentElement.classList.remove('error-invalid');
}else if(input.value !== '' && input.value.match(/^[0-9]+$/) === null){ // wil return null if value has anything accept number
input.parentElement.parentElement.classList.remove('error-empty');
input.parentElement.parentElement.classList.add('error-invalid');
}else{
input.parentElement.parentElement.classList.remove('error-empty');
input.parentElement.parentElement.classList.remove('error-invalid');
}
}
const containsOtherInput = function(input){
if(input.value === ''){
input.parentElement.classList.add('error-empty');
input.parentElement.classList.remove('error-invalid');
}else if(input.value !== '' && input.value.match(/^[0-9]+$/) === null){
input.parentElement.classList.remove('error-empty');
input.parentElement.classList.add('error-invalid');
}else{
input.parentElement.classList.remove('error-empty');
input.parentElement.classList.remove('error-invalid');
}
}
modalClose.addEventListener('click',()=>{
modal.style.display = "none";
})
.input-field .error{
color: red;
font-size: .7rem;
display: none;
}
.input-field.error-empty .empty{
display: block;
}
.input-field.error-invalid .invalid{
display: block;
}
.modal{
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: none;
background:white;
}
<form>
<div class="input-field">
<label for="name">Cardholder Name</label>
<input type="text" placeholder="e.g. Jane Appleseed" id="name" name="name" maxlength="25" class="name-input">
<p class="error empty">Can't be blank</p>
<p class="error invalid">Wrong format, letters only</p>
</div>
<div class="input-field">
<label for="number">Card Number</label>
<input type="text" placeholder="e.g. 1234 5678 9123 0000" id="number" name="number" minlength="16" maxlength="16" class="number-input">
<p class="error empty">Can't be blank</p>
<p class="error invalid">Wrong format, numbers only</p>
</div>
<div class="flex-row">
<div class="input-field date-container">
<label id='date'>Exp. Date (MM/YY)</label>
<div class="date-input">
<input type='text' placeholder="MM" id='month' name="month" aria-labelledby='date' class="date month-input" maxlength="2"/>
<input type='text' placeholder="YY" id='year' name="year" aria-labelledby='date' class="date year-input" maxlength="2"/>
</div>
<p class="error empty">Can't be blank</p>
<p class="error invalid">Wrong format, numbers only</p>
</div>
<div class="input-field">
<label for="cvc">CVC</label>
<input type="text" placeholder="e.g. 123" id="cvc" name="cvc" maxlength="4" class="cvc-input">
<p class="error empty">Can't be blank</p>
<p class="error invalid">Wrong format, numbers only</p>
</div>
</div>
<button type="submit" class="btn">Confirm</button>
</form>
<section class="modal">
<img src="./images/icon-complete.svg" alt="">
<h2>Thank you!</h2>
<p>We've added your card details</p>
<button type="button" class="btn close">Continue</button>
</section>
Classic bug: the result "variable" (here: visibility) gets set after every check, so it will contain the result of the last check and nothing else. Instead you should assume success at the beginning, and only set on failure of a check (and never set to success again). Then if any check fails, the entire thing will fail too.
const form = document.querySelector('form');
const inputs = document.querySelectorAll('input');
const modal = document.querySelector('.modal');
const modalClose = document.querySelector('.close');
form.addEventListener('submit', (e) => {
e.preventDefault();
modal.style.display = "block"; // assume things go well
inputs.forEach(input => {
if (input.classList.contains('name-input')) {
containsNameInput(input)
} else if (input.classList.contains('date')) {
containsDateInput(input)
} else {
containsOtherInput(input)
}
if (input.parentElement.classList.contains('error-empty') ||
input.parentElement.classList.contains('error-invalid') ||
input.parentElement.parentElement.classList.contains('error-invalid') ||
input.parentElement.parentElement.classList.contains('error-empty')) {
modal.style.display = 'none'; // act when they do not
// }else{
// modal.style.display = "block";
}
})
})
const containsNameInput = function(input) {
if (input.value === '') {
input.parentElement.classList.add('error-empty');
input.parentElement.classList.remove('error-invalid');
} else if (input.value !== '' && input.value.match(/^[0-9]+$/) !== null) {
input.parentElement.classList.remove('error-empty');
input.parentElement.classList.add('error-invalid');
} else {
input.parentElement.classList.remove('error-empty');
input.parentElement.classList.remove('error-invalid');
}
}
const containsDateInput = function(input) {
if (input.value === '') {
input.parentElement.parentElement.classList.add('error-empty');
input.parentElement.parentElement.classList.remove('error-invalid');
} else if (input.value !== '' && input.value.match(/^[0-9]+$/) === null) { // wil return null if value has anything accept number
input.parentElement.parentElement.classList.remove('error-empty');
input.parentElement.parentElement.classList.add('error-invalid');
} else {
input.parentElement.parentElement.classList.remove('error-empty');
input.parentElement.parentElement.classList.remove('error-invalid');
}
}
const containsOtherInput = function(input) {
if (input.value === '') {
input.parentElement.classList.add('error-empty');
input.parentElement.classList.remove('error-invalid');
} else if (input.value !== '' && input.value.match(/^[0-9]+$/) === null) {
input.parentElement.classList.remove('error-empty');
input.parentElement.classList.add('error-invalid');
} else {
input.parentElement.classList.remove('error-empty');
input.parentElement.classList.remove('error-invalid');
}
}
modalClose.addEventListener('click', () => {
modal.style.display = "none";
})
.input-field .error {
color: red;
font-size: .7rem;
display: none;
}
.input-field.error-empty .empty {
display: block;
}
.input-field.error-invalid .invalid {
display: block;
}
.modal {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: none;
background: white;
}
<form>
<div class="input-field">
<label for="name">Cardholder Name</label>
<input type="text" placeholder="e.g. Jane Appleseed" id="name" name="name" maxlength="25" class="name-input">
<p class="error empty">Can't be blank</p>
<p class="error invalid">Wrong format, letters only</p>
</div>
<div class="input-field">
<label for="number">Card Number</label>
<input type="text" placeholder="e.g. 1234 5678 9123 0000" id="number" name="number" minlength="16" maxlength="16" class="number-input">
<p class="error empty">Can't be blank</p>
<p class="error invalid">Wrong format, numbers only</p>
</div>
<div class="flex-row">
<div class="input-field date-container">
<label id='date'>Exp. Date (MM/YY)</label>
<div class="date-input">
<input type='text' placeholder="MM" id='month' name="month" aria-labelledby='date' class="date month-input" maxlength="2" />
<input type='text' placeholder="YY" id='year' name="year" aria-labelledby='date' class="date year-input" maxlength="2" />
</div>
<p class="error empty">Can't be blank</p>
<p class="error invalid">Wrong format, numbers only</p>
</div>
<div class="input-field">
<label for="cvc">CVC</label>
<input type="text" placeholder="e.g. 123" id="cvc" name="cvc" minlength="3" maxlength="4" class="cvc-input">
<p class="error empty">Can't be blank</p>
<p class="error invalid">Wrong format, numbers only</p>
</div>
</div>
<button type="submit" class="btn">Confirm</button>
</form>
<section class="modal">
<img src="./images/icon-complete.svg" alt="">
<h2>Thank you!</h2>
<p>We've added your card details</p>
<button type="button" class="btn close">Continue</button>
</section>
According to internet sources, CVC is either 3 or 4 digits, so added a minlength="3".
html does all the blank validation by itself. i am adding required attribute on every input tag
const form = document.querySelector('form');
const inputs = document.querySelectorAll('input');
const modal = document.querySelector('.modal');
const modalClose = document.querySelector('.close');
form.addEventListener('submit', (e) => {
e.preventDefault();
inputs.forEach(input => {
if (input.classList.contains('name-input')) {
containsNameInput(input)
} else if (input.classList.contains('date')) {
containsDateInput(input)
} else {
containsOtherInput(input)
}
})
})
inputs.forEach(input => {
if (input.parentElement.classList.contains('error-empty')
|| input.parentElement.classList.contains('error-invalid')
|| input.parentElement.parentElement.classList.contains('error-invalid')
|| input.parentElement.parentElement.classList.contains('error-empty')) {
modal.style.display = "block";
} else {
modal.style.display = "none";
}
})
const containsNameInput = function (input) {
if (input.value === '') {
input.parentElement.classList.add('error-empty');
input.parentElement.classList.remove('error-invalid');
} else if (input.value !== '' && input.value.match(/^[0-9]+$/) !== null) {
input.parentElement.classList.remove('error-empty');
input.parentElement.classList.add('error-invalid');
}
else {
input.parentElement.classList.remove('error-empty');
input.parentElement.classList.remove('error-invalid');
}
}
const containsDateInput = function (input) {
if (input.value === '') {
input.parentElement.parentElement.classList.add('error-empty');
input.parentElement.parentElement.classList.remove('error-invalid');
} else if (input.value !== '' && input.value.match(/^[0-9]+$/) === null) { // wil return null if value has anything accept number
input.parentElement.parentElement.classList.remove('error-empty');
input.parentElement.parentElement.classList.add('error-invalid');
} else {
input.parentElement.parentElement.classList.remove('error-empty');
input.parentElement.parentElement.classList.remove('error-invalid');
}
}
const containsOtherInput = function (input) {
if (input.value === '') {
input.parentElement.classList.add('error-empty');
input.parentElement.classList.remove('error-invalid');
} else if (input.value !== '' && input.value.match(/^[0-9]+$/) === null) {
input.parentElement.classList.remove('error-empty');
input.parentElement.classList.add('error-invalid');
} else {
input.parentElement.classList.remove('error-empty');
input.parentElement.classList.remove('error-invalid');
}
}
modalClose.addEventListener('click', () => {
modal.style.display = "none";
})
.input-field .error{
color: red;
font-size: .7rem;
display: none;
}
.input-field.error-empty .empty{
display: block;
}
.input-field.error-invalid .invalid{
display: block;
}
.modal{
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: none;
background:white;
}
<form>
<div class="input-field">
<label for="name">Cardholder Name</label>
<input type="text" placeholder="e.g. Jane Appleseed" id="name" name="name" maxlength="25" class="name-input" >
<p class="error empty">Can't be blank</p>
<p class="error invalid">Wrong format, letters only</p>
</div>
<div class="input-field">
<label for="number">Card Number</label>
<input type="text" placeholder="e.g. 1234 5678 9123 0000" id="number" name="number" minlength="16" maxlength="16" class="number-input" >
<p class="error empty">Can't be blank</p>
<p class="error invalid">Wrong format, numbers only</p>
</div>
<div class="flex-row">
<div class="input-field date-container">
<label id='date'>Exp. Date (MM/YY)</label>
<div class="date-input">
<input type='text' placeholder="MM" id='month' name="month" aria-labelledby='date' class="date month-input" maxlength="2" />
<input type='text' placeholder="YY" id='year' name="year" aria-labelledby='date' class="date year-input" maxlength="2"/>
</div>
<p class="error empty">Can't be blank</p>
<p class="error invalid">Wrong format, numbers only</p>
</div>
<div class="input-field">
<label for="cvc">CVC</label>
<input type="text" placeholder="e.g. 123" id="cvc" name="cvc" maxlength="4" class="cvc-input" >
<p class="error empty">Can't be blank</p>
<p class="error invalid">Wrong format, numbers only</p>
</div>
</div>
<button type="submit" class="btn">Confirm</button>
</form>
<section class="modal">
<img src="./images/icon-complete.svg" alt="">
<h2>Thank you!</h2>
<p>We've added your card details</p>
<button type="button" class="btn close">Continue</button>
</section>

Disable a button if (length < x)

good evening.
I'm a beginner with JavaScript and I'm trying to recreate a specific webpage. There, exists a button that, if the login form doesn't have at least 11 elements on user and 8 on password, the button is disabled.
How can I do this with HTML and JS?
function blockButtonByUser() {
var cpfleng = document.getElementById('.iptuser').length
console.log(cpfleng)
var btnsubmit = document.getElementById('.btnsubmit')
if (cpfleng < 11) {
btnsubmit.disabled = true;
} else {
btnsubmit.disabled = false;
}
}
function blockButtonByPassword() {
var passwordlength = document.getElementById('.iptpassword').length
console.log(cpfleng)
var btnsubmit = document.getElementById('.btnsubmit')
if (passwordlength < 8) {
btnsubmit.disabled = true;
} else {
btnsubmit.disabled = false;
}
}
<header><img src="assets/white.svg" alt="logo nubank" height="80px"></header>
<div class="container">
<h2>Faça seu login</h2>
<div class="form">
<div class="user">
<label for="cpf" class='lbluser'>CPF</label>
<input type="text" name="cpf" id="cpf" class='iptuser'>
<div class="underline"></div>
</div>
<div class="password">
<label for="password" class='lblpassword'>Senha</label>
<input type="password" name="password" id="password" class='iptpassword'>
<div class="underline"></div>
</div>
<input type="submit" value="CONTINUAR" class='btnsubmit'>
</div>
<div class="footer">
<div class="esqueci">
Esqueci minha senha >
</div>
<div class="naocliente">
Ainda não sou cliente >
</div>
</div>
</div>
Thanks for the help!
Here is something like that using an eventListener:
var cpfOkay = false
var passwordOkay = false;
var btnsubmit = document.getElementsByClassName('btnsubmit')[0];
document.getElementById('cpf').addEventListener('input', function(){
btnsubmit = document.getElementsByClassName('btnsubmit')[0];
cpfOkay = false;
if (event.target.value.length >= 11) {
cpfOkay = true;
}
checkBoth();
})
document.getElementById('password').addEventListener('input', function(){
btnsubmit = document.getElementsByClassName('btnsubmit')[0];
passwordOkay = false;
if (event.target.value.length >= 8) {
passwordOkay = true;
}
checkBoth();
})
function checkBoth() {
btnsubmit.disabled = true;
btnsubmit.style.opacity = 0.5;
if (cpfOkay && passwordOkay) {
btnsubmit.disabled = false;
btnsubmit.style.opacity = 1;
}
}
<header><img src="https://placekitten.com/200/300" alt="logo nubank" height="80px"></header>
<div class="container">
<h2>Faça seu login</h2>
<div class="form">
<div class="user">
<label for="cpf" class='lbluser'>CPF</label>
<input type="text" name="cpf" id="cpf" class='iptuser'>
<div class="underline"></div>
</div>
<div class="password">
<label for="password" class='lblpassword'>Senha</label>
<input type="password" name="password" id="password" class='iptpassword'>
<div class="underline"></div>
</div>
<input type="submit" value="CONTINUAR" class='btnsubmit' disabled style="opacity:0.5">
</div>
<div class="footer">
<div class="esqueci">
Esqueci minha senha >
</div>
<div class="naocliente">
Ainda não sou cliente >
</div>
</div>
</div>
You can add event listeners for input event for both the user and password, and based on requirements you can enable or disable the button. You can refactor your code like this:
var cpf = document.getElementById('cpf')
var password = document.getElementById('password')
var btnsubmit = document.getElementById('btnsubmit')
cpf.addEventListener('input', function (evt) {
if(cpf.value.length < 11 || password.value.length < 8){
btnsubmit.disabled = true;
} else {
btnsubmit.disabled = false;
}
});
password.addEventListener('input', function (evt) {
if(cpf.value.length < 11 || password.value.length < 8){
btnsubmit.disabled = true;
} else {
btnsubmit.disabled = false;
}
});
<header><img src="assets/white.svg" alt="logo nubank" height="80px"></header>
<div class="container">
<h2>Faça seu login</h2>
<div class="form">
<div class="user">
<label for="cpf" class='lbluser'>CPF</label>
<input type="text" name="cpf" id="cpf" class='iptuser'>
<div class="underline"></div>
</div>
<div class="password">
<label for="password" class='lblpassword'>Senha</label>
<input type="password" name="password" id="password" class='iptpassword'>
<div class="underline"></div>
</div>
<input type="submit" value="CONTINUAR" class='btnsubmit' id='btnsubmit' disabled>
</div>
<div class="footer">
<div class="esqueci">
Esqueci minha senha >
</div>
<div class="naocliente">
Ainda não sou cliente >
</div>
</div>
</div>
<script src="main.js"></script>
You have a few issues. One was getElementById on classes. One was no event handler. Lastly, you were trying to get the length on the element, but not the length of the value.
This should work:
document.querySelector('.btnsubmit').addEventListener('click', e =>{
blockButtonByUser();
blockButtonByPassword()
})
function blockButtonByUser(){
var cpfleng = document.querySelector('.iptuser').value.length
console.log(cpfleng)
var btnsubmit = document.querySelector('.btnsubmit')
if (cpfleng < 11) {
btnsubmit.disabled = true;
} else{
btnsubmit.disabled = false;
}
}
function blockButtonByPassword(){
var passwordlength = document.querySelector('.iptpassword').value.length
console.log(passwordlength)
var btnsubmit = document.querySelector('.btnsubmit')
if (passwordlength < 8) {
btnsubmit.disabled = true;
} else{
btnsubmit.disabled = false;
}
}

i have a error while validating my html form with javascript

This is my javascript function.
function shortCutValidation() {
//var txtObjList = document.getElementsByTagName("input");
//for (var i = 0; i < txtObjList.length; i++) {
// if (txtObjList[i].getAttribute("type") == "text" && this.value != "") {
// // success for i+1 textbox
// }
// else {
// $(txtObjList).closest(".errortext").css("display", "block");
// }
//}
var data = document.getElementsByClassName("w-input");
if (data.length > 0) {
console.log("yes you are in");
for (var i = 0; i < data.length; i++) {
var myvalue = document.getElementsByClassName("w-input");
if (myvalue[i].value == '') {
console.log("yes value is empty"+myvalue[i].value);
$(myvalue[i]).next(".errortext").css("display", "block");
}
else {
console.log("thats ok");
$(data[i]).next(".errortext").css("display", "none");
}
console.log(i);
}
}
}
This is my html code.
<div class="myformgrp w-clearfix w-col">
<div class="w-col w-col-2 w-col-medium-3 w-col-small-12">
<label for="firstname" class="verticle-centerinline">First Name </label>
</div>
<div class="w-col w-col-10 w-col-medium-9 w-col-small-12">
<input type="hidden" id="id" name="id" value="" />
<input type="text" class="w-input" name="fname" id="fname" />
<div class="errortext" style="display:none">required field</div>
</div>
</div>
<div class="myformgrp w-clearfix w-col">
<div class="w-col w-col-2 w-col-medium-3 w-col-small-12">
<label for="firstname" class="verticle-centerinline">Last Name </label>
</div>
<div class="w-col w-col-10 w-col-medium-9 w-col-small-12">
<input type="text" class="w-input" name="lname" id="lname" /><br />
<div class="errortext" style="display:none">required field</div>
</div>
</div>
The problem is that I can't validate all the text box at once
but my for loop is working as expected.
I use jQuery to call the shortCutValidation function.
All I want is when my blur event is called to validate all the text box at once and the error massage should be displayed.
Try This
function validateFormOnSubmit(contact) {
reason = "";
reason += validateName(contact.name);
reason += validateEmail(contact.email);
reason += validatePhone(contact.phone);
reason += validatePet(contact.pet);
reason += validateNumber(contact.number);
reason += validateDisclaimer(contact.disclaimer);
if (reason.length > 0) {
return false;
} else {
return false;
}
}
// validate required fields
function validateName(name) {
var error = "";
if (name.value.length == 0) {
name.style.background = 'Red';
document.getElementById('name-error').innerHTML = "The required field has not been filled in";
var error = "1";
} else {
name.style.background = 'White';
document.getElementById('name-error').innerHTML = '';
}
return error;
}
// validate email as required field and format
function trim(s) {
return s.replace(/^\s+|\s+$/, '');
}
function validateEmail(email) {
var error = "";
var temail = trim(email.value); // value of field with whitespace trimmed off
var emailFilter = /^[^#]+#[^#.]+\.[^#]*\w\w$/;
var illegalChars = /[\(\)\<\>\,\;\:\\\"\[\]]/;
if (email.value == "") {
email.style.background = 'Red';
document.getElementById('email-error').innerHTML = "Please enter an email address.";
var error = "2";
} else if (!emailFilter.test(temail)) { //test email for illegal characters
email.style.background = 'Red';
document.getElementById('email-error').innerHTML = "Please enter a valid email address.";
var error = "3";
} else if (email.value.match(illegalChars)) {
email.style.background = 'Red';
var error = "4";
document.getElementById('email-error').innerHTML = "Email contains invalid characters.";
} else {
email.style.background = 'White';
document.getElementById('email-error').innerHTML = '';
}
return error;
}
// validate phone for required and format
function validatePhone(phone) {
var error = "";
var stripped = phone.value.replace(/[\(\)\.\-\ ]/g, '');
if (phone.value == "") {
document.getElementById('phone-error').innerHTML = "Please enter a phone number";
phone.style.background = 'Red';
var error = '6';
} else if (isNaN(parseInt(stripped))) {
var error = "5";
document.getElementById('phone-error').innerHTML = "The phone number contains illegal characters.";
phone.style.background = 'Red';
} else if (stripped.length < 10) {
var error = "6";
document.getElementById('phone-error').innerHTML = "The phone number is too short.";
phone.style.background = 'Red';
} else {
phone.style.background = 'White';
document.getElementById('phone-error').innerHTML = '';
}
return error;
}
function validatePet(pet) {
if ((contact.pet[0].checked == false) && (contact.pet[1].checked == false) && (contact.pet[2].checked == false)) {
document.getElementById('pet-error').innerHTML = "Pet required";
var error = "2";
} else {
document.getElementById('pet-error').innerHTML = '';
}
return error;
}
function validateNumber(number) {
var num = document.forms["contact"]["number"];
var y = num.value;
if (!isNaN(y)) {
//alert('va');
if (y < 0 || y > 50) {
//Wrong
number.style.background = 'Red';
document.getElementById("number-error").innerHTML = "Must be between 0 and 50.";
var error = "10";
} else {
//Correct
number.style.background = 'White';
document.getElementById("number-error").innerHTML = "";
}
return error;
} else {
document.getElementById("number-error").innerHTML = "Must be a number.";
var error = "3";
}
return error;
}
function validateDisclaimer(disclaimer) {
var error = "";
if (document.getElementById("disclaimer").checked === false) {
document.getElementById('disclaimer-error').innerHTML = "Required";
var error = "4";
} else {
document.getElementById('disclaimer-error').innerHTML = '';
}
return error;
}
.error {
color: #990000;
}
input::-webkit-input-placeholder {
color: white !important;
}
input:-moz-placeholder { /* Firefox 18- */
color: white !important;
}
input::-moz-placeholder { /* Firefox 19+ */
color: white !important;
}
input:-ms-input-placeholder {
color: white !important;
}
<form id="contact" name="contact" onsubmit="return validateFormOnSubmit(this)" action="" method="post">
<div>
<label>First Name</label>
<input placeholder="First Name" type="text" name="name" id="name" tabindex="1" autofocus />
<div id="name-error" class="error"></div>
</div>
<div>
<label>Nickname</label>
<input placeholder="Nickname" type="text" name="nickname" id="nickname" tabindex="2" autofocus />
</div>
<div>
<label>Email</label>
<input placeholder="Email" type="email" name="email" id="email" tabindex="3" autofocus />
<div id="email-error" class="error"></div>
</div>
<div>
<label>Phone</label>
<input placeholder="Phone" type="tel" name="phone" id="phone" tabindex="4" autofocus />
<div id="phone-error" class="error"></div>
</div>
<div>
<label>I prefer</label>
<input type="radio" name="pet" id="Dogs" tabindex="5" autofocus />Dogs
<input type="radio" name="pet" id="Cats" tabindex="6" autofocus />Cats
<input type="radio" name="pet" id="Neither" tabindex="7" autofocus />Neither
<div id="pet-error" class="error"></div>
</div>
<div>
<label>My favorite number between 1 and 50</label>
<input placeholder="Favorite number between 1 and 50" type="text" name="number" id="number" tabindex="8" autofocus />
<div id="number-error" class="error"></div>
</div>
<div>
<label>Disclaimer</label>
<input type="checkbox" name="disclaimer" id="disclaimer" tabindex="9" autofocus />I confirm that all the above information is true.
<div id="disclaimer-error" class="error"></div>
</div>
<div>
<button type="submit" name="submit" id="submit" tabindex="10">Send</button>
</div>
</form>
Happy Coding

Box with two form options

I have a form that displays a box that has two options, one is "accepted" and the other "not accept". It turns out that when the user uses to send the email, he can send it with the button marked "not accept". Is there any way that I can make it validate?
HTML
<div class="form">
<h4>Valor do consórcio: <span class="slider-value quote-form-element" data-name="Valor | Automóvel" data-slider-id="consorcio-auto">R$ <span></span></span></h4>
<div class="slider" data-slider-min="20000" data-slider-max="100000" data-slider-start="23192" data-slider-step="1000" data-slider-id="consorcio-auto"></div>
<h4>Seus dados:</h4>
<input type="text" name="Nome" placeholder="Nome..." class="quote-form-element" />
<input type="text" name="Cidade" placeholder="Cidade/UF..." class="quote-form-element quote-form-client-email last" />
<input type="text" name="Número de Telefone" placeholder="Telefone..." class="quote-form-element telefone" />
<input type="text" name="Endereço de Email" placeholder="E-mail..." class="quote-form-element quote-form-client-email last contact_email" />
<h4>Política de Privacidade</h4>
<div class="checkbox quote-form-element" data-checked="yes" data-name="Política de Privacidade">
<span class="checkbox-status"><i class="fa fa-check"></i></span>
<span class="checkbox-values">
<span class="checkbox-value-checked" style="font-size: 12px">Li e aceito a politica de privacidade</span>
<span class="checkbox-value-unchecked">Não aceito</span>
</span>
</div>
<button class="button button-navy-blue send-quote" type="button">Simular meu consórcio <i class="fa fa-paper-plane-o"></i></button>
<div class="quote-form-thanks">
<div class="quote-form-thanks-content">
Obrigado pelo seu interesse, retornaremos em breve ;).
<span class="quote-form-thanks-close">Fechar</span>
</div>
</div>
</div>
Javascript
$('.send-quote').click(function () {
var quoteForm = $(this).parent();
var quoteFormParent = quoteForm.parent().parent();
var insuranceType = quoteFormParent.data('quote-form-for');
var fields = {};
var fieldID = 0;
var fieldName = '';
var fieldValue = '';
var clientName = '';
var clientEmail = '';
var errorFound = false;
quoteForm.find('.quote-form-element').each(function (fieldID) {
fieldName = $(this).attr('name');
if (typeof fieldName == 'undefined' || fieldName === false) {
fieldName = $(this).data('name');
}
if ($(this).hasClass('checkbox')) {
fieldValue = $(this).data('checked') == 'yes' ? $(this).children('.checkbox-values').children('.checkbox-value-checked').text() : $(this).children('.checkbox-values').children('.checkbox-value-unchecked').text();
}
else {
fieldValue = $(this).is('input') || $(this).is('select') ? $(this).val() : $(this).text();
if (($(this).is('input') && fieldValue == '') || ($(this).is('select') && fieldValue == '-')) {
errorFound = true;
$(this).addClass('error');
}
else {
$(this).removeClass('error');
}
}
if ($(this).hasClass('quote-form-client-name')) clientName = $(this).val();
if ($(this).hasClass('quote-form-client-email')) clientEmail = $(this).val();
fields[fieldID] = { 'name': fieldName, 'value': fieldValue };
fieldID++;
});
if (errorFound == false) {
$.ajax({
url: '_assets/submit.php',
data: { 'send': 'quote-form', 'values': fields, 'clientName': clientName, 'clientEmail': clientEmail },
type: 'post',
success: function (output) {
quoteForm.children('.quote-form-thanks').fadeIn(300);
}
});
}
});
page that displays the contents in the "Simulation".
So you need to check if "no accept" is checked or not using radio inputs.
$('.send-quote').click(function() {
if ($('[name=terms]:checked').val() === 'no') {
console.log('got an error');
} else {
console.log('all good');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="terms" value="yes" checked></input>
<label for="terms">Do accept terms</label>
<br>
<input type="radio" name="terms" value="no"></input>
<label for="terms">Don't accept terms</label>
<br>
<button type="button" class="send-quote">Send Quote</button>

onsubmit attribute not work

Hello I trying to validate my form using onsubmit attribute. But it does not work. And the funniest thing in this story - this works properly only 2 days ago.
Form tag :
<form action="../actionHandlers/registrationHandler.php" onsubmit="return validateRegistrationForm()" method="post" name="reg_form" enctype="multipart/form-data" id="reg_form">
Validate function:
function validateRegistrationForm() {
var errors = [];
if (document.forms['reg_form']['username'].value.length == 0) {
var usernameErrorMessage = localStorage.getItem('emptyLoginError');
errors.push(usernameErrorMessage);
}
if (document.forms['reg_form']['password'].value.length == 0) {
var passwordErrorMessage = localStorage.getItem('emptyPasswordError');
errors.push(passwordErrorMessage);
}
if (!validateEmail(document.forms['reg_form']['email'].value)) {
var emailErrorMessage = localStorage.getItem('emailInvalidError');
errors.push(emailErrorMessage);
}
if (errors.length > 0) {
var htmlErrors = '';
for (var i = 0; i < errors.length; i++) {
htmlErrors += errors[i] + "<br />";
}
document.getElementById("error_message").innerHTML = htmlErrors;
return false;
} else {
return true;
}
}
Where is my mistake? Please help)
Validate email:
function validateEmail(email) {
var pattern = /^([a-zA-Z0-9_.-])+#([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
return pattern.test(email);
}
Inputs:
<div>
<label for="username" id="username_label"><?php echo $languageArray['USERNAME'] ?></label><span id="required_mark">*</span><br/>
<input type="text" name="username" id="username_field" class="input_form_fields">
</div>
<div>
<label for="password"><?php echo $languageArray['PASSWORD'] ?></label><span id="required_mark">*</span><br/>
<input type="password" name="password" id="password_field" class="input_form_fields">
</div>
<div>
<label for="email"><?php echo $languageArray['EMAIL'] ?></label><span id="required_mark">*</span><br/>
<input type="text" name="email" id="email_field" class="input_form_fields">
</div>
Try this code, I have tested it and its working:
<form action="../actionHandlers/registrationHandler.php" onsubmit="return validateRegistrationForm()" method="post" name="reg_form" enctype="multipart/form-data" id="reg_form">
<div>
<label for="username" id="username_label"><?php echo (isset($languageArray['USERNAME']) ? $languageArray['USERNAME'] : "email"); ?></label><span id="required_mark">*</span><br/>
<input type="text" name="username" id="username_field" class="input_form_fields">
</div>
<div>
<label for="password"><?php echo (isset($languageArray['PASSWORD']) ? $languageArray['PASSWORD'] : "email"); ?></label><span id="required_mark">*</span><br/>
<input type="password" name="password" id="password_field" class="input_form_fields">
</div>
<div>
<label for="email"><?php echo (isset($languageArray['EMAIL']) ? $languageArray['EMAIL'] : "email"); ?></label><span id="required_mark">*</span><br/>
<input type="text" name="email" id="email_field" class="input_form_fields">
</div>
<input type="submit">
</form>
And the JS:
function validateEmail(email) {
var pattern = /^([a-zA-Z0-9_.-])+#([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
return pattern.test(email);
}
function validateRegistrationForm(e) {
var errors = [];
if (document.forms['reg_form']['username'].value.length == 0) {
var usernameErrorMessage = localStorage.getItem('emptyLoginError') ? localStorage.getItem('emptyLoginError') : "username error";
errors.push(usernameErrorMessage);
}
if (document.forms['reg_form']['password'].value.length == 0) {
var passwordErrorMessage = localStorage.getItem('emptyPasswordError') ? localStorage.getItem('emptyPasswordError') : "password error";
errors.push(passwordErrorMessage);
}
if (!validateEmail(document.forms['reg_form']['email'].value)) {
var emailErrorMessage = localStorage.getItem('emailInvalidError') ? localStorage.getItem('emailInvalidError') : "email error";
errors.push(emailErrorMessage);
}
if (errors.length > 0) {
var htmlErrors = '';
for (var i = 0; i < errors.length; i++) {
htmlErrors += errors[i] + "<br />";
}
if(document.getElementById("error_message")){
document.getElementById("error_message").innerHTML = htmlErrors;
}
return false;
} else {
return true;
}
}
The way I see it the problem were caused by any of the following:
localStorage.getItem notice that you don't even check to see if the key exists.
echo $languageArray['PASSWORD'] again there is no check at all, although I'm sure its not php error but its good to check before you echo.
document.getElementById("error_message"), well you use the innerHTML but the document.getElementById my return undefined.
Conclusion:
The code should work.
But:
You say it worked before, I'm thinking you have touched the html in one way or another, if its not the html check the localStorage keys.

Categories

Resources