validity API to validate a form

  forms, html, javascript

I’m trying to validate a form with validity API, but have some issues (2 to be precise) . One for valueMissing where the textContent couldn’t be displayed and the second when submitting the form (all fiels are corect then) : nothing happen, I can’t see the console.log. Here is the code

html

const formValid = document.getElementById('myButton');
formValid.addEventListener('click', valid);
 
 
// function valid() : allow sending form after checking it
function valid(e) {
    e.preventDefault();
    let isFormOk = true;

 
    let fname = document.getElementById('fname');
    let missFname = document.getElementById('fname_missing');
    let firstNameValue = document.getElementById('fname').value;
 
    let email = document.getElementById('email');
    let missEmail = document.getElementById('email_missing');
    let emailValue = document.getElementById('email').value;
 
    let fnameValid = /^[a-zA-ZéèîïÉÈÎÏ][a-zéèêàçîï]+([-'s][a-zA-ZéèîïÉÈÎÏ][a-zéèêàçîï]+)?$/;
    let emailValid = /^[email protected][a-zA-Z_]+?.[a-zA-Z]{2,3}$/;
 
    //Validate the firstname :
    if (fname.validity.valueMissing) { //if the field is empty
        missFname.textContent = 'Enter your firstname please!';
        missFname.style.color = 'red';
        isFormOk = false;
    }
    if (fnameValid.test(fname.value) == false) { // if the format is incorrect
        missFname.textContent = 'Incorrect format';
        missFname.style.color = 'black';
        isFormOk = false;
    }
 
    
    //Validate the email :
    if (email.validity.valueMissing) {
        missEmail.textContent = 'Email missing';
        missEmail.style.color = 'red';
        isFormOk = false;
    }
    if (emailValid.test(email.value) == false) {
        missEmail.textContent = 'Incorrect format';
        missEmail.style.color = 'black';
        isFormOk = false;
    }
 
    if (isFormOk) {
        let contact = {
            firstNameValue,
            emailValue
        };
console.log(contact);
}
<form novalidate id="myForm">
    <div class="form-group">
        <input type="text" class="form-control" name="fname" id="fname" required>
        <span id="fname_missing"></span>
    </div>
 
    <div class="form-group">
        <input type="email" class="form-control" name="email" id="email" required>
        <span id="email_missing" class="errorMail" aria-live="polite"></span>
    </div>
    <div class="form-group">
        <button id="myButton" name="myButton" type="submit">Confirm</button>
</div>
</form>

Source: Ask Javascript Questions

LEAVE A COMMENT