Javascript Form Validation Operations

I would like to share some useful information with you for validating form elements in Javascript.

First of all, as you know, we could control the correctness of form elements by putting attributes such as required min max minlength maxlength.

For example;

<form action="" method="post">
    <input type="text" id="username" name="username" maxlength="20" required> <br>
    <input type="email" name="email" required> <br>
    <input type="password" required name="password" minlength="3" maxlength="20"> <br>
    <button type="submit">Submit</button>
</form>

If you press the Submit button, you can see some values that the browser outputs.

Now add the following attribute to the form tag to cancel these values.

<form novalidate="novalidate">

Those values will no longer appear, but it still won't submit until the form is valid. Now we can take and show these values ourselves.

For example;

const formElem = document.querySelector('form')
formElem.addEventListener('submit', function(e) {
    e.preventDefault();

    [...this.elements].forEach(input => {
       if (!input.checkValidity()) {
           console.log(input.validationMessage); // error message
       } else {
           // form element is valid
       }
    })

    if (this.checkValidity() === true){
        // all items in the form are valid
    }

}, true);

In other words, we can control the form elements and the form itself with the checkValidity() method. It is valid if it returns true, if it returns false, it is invalid.

Accordingly, if the form elements are invalid, we can get the relevant message from the validationMessage prop.

If we can get it, it means we can evaluate it the way we want. First of all, let's turn the control operations of these form elements into a function. And let's do the following in this function, if the related form element is wrong, let's write the error message with the small tag right after it. But let's check this while writing, if the error message has already been added, let's not add it again. And finally, we will need to clear this error when the form element is valid.

function formControl(input) {
    if (!input.checkValidity()) {
        let error
        if (input.nextElementSibling?.className === 'error-msg'){
            error = input.nextElementSibling
        } else {
            error = document.createElement('small')
        }
        error.className = 'error-msg'
        error.innerText = input.validationMessage
        input.insertAdjacentElement('afterend', error)
    } else {
        const errorMsg = input.nextElementSibling
        if (errorMsg) {
            errorMsg.remove()
        }
    }
}

Now we can integrate our previous form submit sample with it.

const formElem = document.querySelector('form')
formElem.addEventListener('submit', function(e) {
    e.preventDefault();

    // let's check all form elements
    [...this.elements].forEach(input => formControl(input))

    if (this.checkValidity() === true){
        // all items in the form are valid
    }

}, true);

In addition, we need to define events such as change keyup to control the form elements instantly. We can do it like this

[...formElem.elements].forEach(input => {
    ['change', 'keyup'].forEach(method => input.addEventListener(method, e => formControl(e.target)))
})

In this way, we have defined change and keyup events for all form elements in the related form. The formControl function will run for every change and will print new error messages if any, otherwise it will remove the relevant error message field from the page.

Receiving and Submitting Form Values

If you remember, we were checking whether all the items in the form were valid by checking the checkValidity() method for the form in the submit event. Now let's edit the relevant part as follows;

if (this.checkValidity() === true){
    new FormData(formElem);
}

In this way, we can now listen to the formata event. The FormData() object will trigger this event.

formElem.addEventListener('formdata', function(e) {

    // all form data
    let data = e.formData;

    // you can crown this with an ajax request if you wish
    var request = new XMLHttpRequest();
    request.open("POST", "/ajax.php");
    request.addEventListener('load', function(response) {
        console.log(response)
    });
    request.send(data);
});
Comments

There are no comments, make the firs comment