in my simple form, I use this simple client-side validation.
The validation start when I press SUBMIT (change style input and span of form).
How can I validate the input even when the user fills in the field without going through the SUBMIT?
STYLE
<style>
.msc-login-form-input {
display: flex;
}
.msc-login-form-input.success > input {
color: #3F4254;
background-color: #ffffff;
}
.msc-login-form-input.errore > input {
background-color: #4d40ff;
color: #ffffff;
}
.msc-login-form-input.errore > input::-webkit-input-placeholder {
color: #ffffff;
}
.msc-login-form-input.errore > input:-ms-input-placeholder {
color: #ffffff;
}
.msc-login-form-input.errore > input::placeholder {
color: #ffffff;
}
.msc-login-form-input > span {
width: 35px;
background-color: rgba(0,0,0,0.05);
min-height: 100%;
align-items: center;
justify-content: center;
text-align: center;
display: flex;
}
.msc-login-form-input > span::before {
font-family: "Font Awesome 5 Free";
font-weight: 900;
content: "f100";
}
.msc-login-form-input.success > span::before {
content: "f00c";
color:#FF1493;
}
.msc-login-form-input.errore > span::before {
content: "f00d";
color:#4d40ff;
}
</style>
HTML and JS
This script checks the internal elements of the form. If, when I click on SUBMIT the fields are empty, then, it highlights the inputs with different styles and loads me different icons in the SPANs tag.
<form id="signinform" method="post" action="#" class="wp-user-form" autocomplete="off">
<div class="msc-login-form-input">
<input type="text" name="log" value="" id="user_login" placeholder="prova" required/>
<span></span> </div>
<div class="msc-login-form-input">
<input type="password" name="pwd" value="" id="user_pass" placeholder="prova" required/>
<span></span> </div>
<div class="msc-login-form-input-sendh">
<input type="submit" id="submit-login" name="submit-login" value="Submit" class="user-submit" />
</div>
<script>
// ___________________________________________________________________
// validate contact form
const myform = document.getElementById('signinform');
myform.noValidate = true;
// custom form validation
myform.addEventListener('submit', validateForm);
// stop submission of valid form for demo
myform.addEventListener('submit', e => {
e.preventDefault();
const fd = new FormData(e.target);
for (const [name, value] of fd.entries()) {
console.log(name + ': ' + value);
}
});
// form validation
function validateForm(e) {
const
form = e.target,
field = Array.from(form.elements);
// reset fields
field.forEach(i => {
i.parentElement.classList.remove('errore');
i.parentElement.classList.add('success');
});
if (!form.checkValidity()) {
// form is invalid - cancel submit
e.preventDefault();
e.stopImmediatePropagation();
// apply invalid class
field.forEach(i => {
if (!i.checkValidity()) {
// field is invalid - add class
i.parentElement.classList.add('errore');
i.parentElement.classList.remove('success');
}
});
}
}
</script>
</form>
Thanks