Html5 form validation with JavaScript

This post shows you how to customize browser built-in Html5 form validation with JavaScript and CSS. You will be able to validate from JavaScript, add customized error messages, perform remote validation, perform confirmation validation, perform file validation and apply customized styling to error messages.

We are going to use built-in form validation (Html5) as much as possible, it is faster than JavaScript validation and it means less work for us. We will need JavaScript, the Constraint Validation API and CSS to add more rules, customize messages and to style error messages.

This plugin for Html5 validation is designed so that you have a choice to add some custom error messages and to style some error messages. Browser built-in error messages will be used if you don’t add custom error messages and built-in styling will be used if you don’t add custom error containers.

JavaScript

This is the JavaScript that handles all forms of validation, validation can be triggered from a submit event or by calling the public function named valid.

var annytab = annytab || {};
annytab.validation = (function ()
{
    'use_strict';

    // Variables
    var forms = document.getElementsByTagName('form');

    // Loop forms
    for (var i = 0; i < forms.length; i++) {

        // Set forms to not validate, this code will handle validation
        forms[i].noValidate = true;

        // Add submit listener
        window.onload = forms[i].addEventListener('submit', async function (event) {

            // Prevent the form from submitting
            event.preventDefault();

            // Validate a form
            if (await validate(this) === true)
            {
                // Submit the form
                this.submit();
            }

        }, false);

        // Get elements in the form
        var elements = forms[i].querySelectorAll('input, select, textarea');

        // Add listener for elements
        for (var j = 0; j < elements.length; j++)
        {
            // Add input listener
            window.onload = elements[j].addEventListener('input', function () {

                // Variables
                var error_output = null;

                // Find equalto element
                var confirmation = this.form.querySelector('[data-validation-equalto="' + this.getAttribute('name') + '"]');
                
                // Remove confirmation error
                if (confirmation !== null)
                {
                    error_output = this.form.querySelector('[data-error-for="' + confirmation.name + '"]');
                    if (error_output !== null) { error_output.innerHTML = ''; }
                }

                // Remove all errors for this element
                error_output = this.form.querySelector('[data-error-for="' + this.getAttribute('name') + '"]');
                if (error_output !== null) { error_output.innerHTML = ''; }

            }, false);
        }

    } // End of for (var i = 0; i < forms.length; i++)

    // Validate a form
    async function validate(form)
    {
        // Get elements in the form
        var elements = form.querySelectorAll('input, select, textarea');

        // Loop elements
        for (i = 0; i < elements.length; i++) {

            // Get the control
            var ctrl = elements[i];

            // Check if the control should be validated
            if (ctrl.willValidate === false) { continue; }

            // Get error message container
            var error_output = form.querySelector('[data-error-for="' + ctrl.getAttribute('name') + '"]');

            // Get custom validation attributes
            var data_validation_remote = ctrl.getAttribute('data-validation-remote');
            var data_validation_equalto = ctrl.getAttribute('data-validation-equalto');
            var data_validation_file = ctrl.getAttribute('data-validation-file');

            // Get custom error attributes
            var data_error_input = ctrl.getAttribute('data-error-input');
            var data_error_pattern = ctrl.getAttribute('data-error-pattern');
            var data_error_range = ctrl.getAttribute('data-error-range');
            var data_error_step = ctrl.getAttribute('data-error-step');
            var data_error_length = ctrl.getAttribute('data-error-length');
            var data_error_type = ctrl.getAttribute('data-error-type');
            var data_error_required = ctrl.getAttribute('data-error-required');
            var data_error_remote = ctrl.getAttribute('data-error-remote');
            var data_error_equalto = ctrl.getAttribute('data-error-equalto');
            var data_error_file = ctrl.getAttribute('data-error-file');

            // Reset custom validation
            ctrl.setCustomValidity('');

            // Check for errors
            if (ctrl.validity.badInput === true) // parsing error
            {
                if (data_error_input !== null) { ctrl.setCustomValidity(data_error_input); }
            }
            else if (ctrl.validity.patternMismatch === true) // pattern
            {
                if (data_error_pattern !== null) { ctrl.setCustomValidity(data_error_pattern); }
            }
            else if (ctrl.validity.rangeOverflow === true || ctrl.validity.rangeUnderflow === true) // max value or min value
            {
                if (data_error_range !== null) { ctrl.setCustomValidity(data_error_range); }
            }
            else if (ctrl.validity.stepMismatch === true) // step value
            {
                if (data_error_step !== null) { ctrl.setCustomValidity(data_error_step); }
            }
            else if (ctrl.validity.tooLong === true || ctrl.validity.tooShort) // max length or min length
            {
                if (data_error_length !== null) { ctrl.setCustomValidity(data_error_length); }
            }
            else if (ctrl.validity.typeMismatch === true) // input type error
            {
                if (data_error_type !== null) { ctrl.setCustomValidity(data_error_type); }
            }
            else if (ctrl.validity.valueMissing === true) // required
            {
                if (data_error_required !== null) { ctrl.setCustomValidity(data_error_required); }
            }
            else if (data_validation_equalto !== null) // confirmation
            {
                if (equaltoValidation(ctrl, data_validation_equalto) === false) { ctrl.setCustomValidity(data_error_equalto); }
            }
            else if (data_validation_file !== null) // File
            {
                if (fileValidation(ctrl, data_validation_file) === false) { ctrl.setCustomValidity(data_error_file); }
            }
            else if (data_validation_remote !== null)
            {
                // Perform remote validation
                if (await remoteValidation(ctrl, data_validation_remote) === false) { ctrl.setCustomValidity(data_error_remote); }
            }

            // Set error message in custom control or report validity
            if (ctrl.validationMessage !== '' && error_output !== null)
            {
                error_output.innerHTML = ctrl.validationMessage;
                ctrl.focus();
            }
            else
            {
                ctrl.reportValidity();
            }
            
        } // for (i = 0; i < elements.length; i++)

        // Return true or false
        return form.checkValidity();

    } // End of the validate form method

    // Perform equalto validation
    function equaltoValidation(ctrl, other_field)
    {
        // Get the value of the other field
        var other_value = document.getElementsByName(other_field)[0].value;

        // Check if values are different
        if (ctrl.value !== other_value)
        {
            return false;
        }

        // Return true
        return true;

    } // End of the equaltoValidation method

    // Perform file validation
    function fileValidation(ctrl, max_size)
    {
        // Make sure that there is files
        if (ctrl.files.length <= 0)
        {
            return true;
        }

        // Check accept attribute
        var accepts = ctrl.getAttribute('accept') !== null ? ctrl.getAttribute('accept').toLowerCase().replace(' ', '').split(',') : null;

        // Loop files
        for (var i = 0; i < ctrl.files.length; i++)
        {
            // Get the file extension
            var extension = ctrl.files[i].name.substring(ctrl.files[i].name.lastIndexOf('.')).toLowerCase();

            // Check for errors
            if (accepts !== null && accepts.includes(extension) === false)
            {
                return false;
            }
            else if (max_size !== null && max_size > 0 &&  ctrl.files[i].size >= max_size)
            {
                return false;
            }
        }

        // Return true
        return true;

    } // End of the fileValidation method

    // Perform remote validation
    async function remoteValidation(ctrl, input)
    {
        // Return a promise
        return new Promise((resolve, reject) => {

            // Get input values
            var values = input.split(',');
            var uri = values[0].trim();
            var fields = [];
            fields.push(ctrl.getAttribute('name'));
            for (var i = 1; i < values.length; i++) { fields.push(values[i].trim()); }

            // Create form data
            var fd = new FormData();
            for (i = 0; i < fields.length; i++) { fd.append(fields[i], document.getElementsByName(fields[i])[0].value); }

            var xhr = new XMLHttpRequest();
            xhr.open('POST', uri, true);
            xhr.onload = function () {

                // Check if the response is successful
                if (xhr.status === 200)
                {
                    // Return a success response
                    if (xhr.response === 'false') { resolve(false); } else { resolve(true); }
                }
                else
                {
                    // Return a reject response
                    reject(xhr.status + ' ' + xhr.statusText);
                }
            };
            xhr.onerror = function ()
            {
                // Return a reject response
                reject('There was a network error.');
            };
            xhr.send(fd);
        });

    } // End of the remoteValidation method

    // Public methods
    return {
        valid: async function (form) {
            return await validate(form);
        }
    };

})();

Example form

This is a form with html syntax and razor syntax, it shows som input elements and includes a method to post the form. You do not need to post the form with JavaScript, you can use a submit button instead.

@{
    // Set the layout for the page
    Layout = "/Views/shared_admin/_standard_layout.cshtml";

    // Get form data
    WebDomain current_domain = ViewBag.CurrentDomain;
    KeyStringList tt = ViewBag.TranslatedTexts;
    AdministratorDocument post = ViewBag.Post;

    // Get translated texts
    string administrator_tt = tt.Get("administrator");
    string new_tt = tt.Get("new");
    string edit_tt = tt.Get("edit");
    string id_tt = tt.Get("id");
    string username_tt = tt.Get("username");
    string password_tt = tt.Get("password");
    string confirm_password_tt = tt.Get("confirm") + " " + tt.Get("password").ToLower();
    string admin_role_tt = tt.Get("role");
    string email_tt = tt.Get("email");
    string save_tt = tt.Get("save");
    string cancel_tt = tt.Get("cancel");

    // Set the title for the page
    if (post.admin_username == "")
    {
        ViewBag.Title = administrator_tt + " - " + new_tt.ToLower();
    }
    else
    {
        ViewBag.Title = administrator_tt + " - " + edit_tt.ToLower();
    }
}

@*Title*@
<h1>@ViewBag.Title</h1>

@*Menu*@
@await Html.PartialAsync("/Views/admin_administrators/_form_menu.cshtml")

@*Main form*@
<form id="inputForm" action="/admin_administrators/edit" method="post" enctype="multipart/form-data">

    @*Hidden data*@
    @Html.AntiForgeryToken()

    @*Id*@
    <div class="annytab-form-label">@id_tt</div>
    <input name="txtId" type="text" class="annytab-form-control" tabindex="-1" readonly value="@post.id" />

    @*Text*@
    <div class="annytab-form-label">@username_tt</div>
    <input name="txtUsername" type="text" class="annytab-form-control" value="@post.admin_username" placeholder="@username_tt" autofocus required
           data-error-required="You must enter a username!" data-validation-remote="/admin_administrators/verify_username,txtId"
           data-error-remote="The username is already in use!" maxlength="10" minlength="2" />
    <div class="validation-error" data-error-for="txtUsername"></div>

    @*Confirmation*@
    <div class="annytab-form-label">@password_tt</div>
    <input name="txtPassword" type="password" class="annytab-form-control" value="" placeholder="@password_tt" />
    <input name="txtConfirmPassword" type="password" class="annytab-form-control" value="" placeholder="@confirm_password_tt"
           data-validation-equalto="txtPassword" data-error-equalto="Passwords does not match!" />
    <div class="validation-error" data-error-for="txtConfirmPassword"></div>

    @*Select*@
    <div class="annytab-form-label">@admin_role_tt</div>
    <select name="selectAdminRole" class="annytab-form-control" required>
        <!option value="">--- Select a role ---</!option>
        <!option value="Administrator" @(post.admin_role == "Administrator" ? "selected" : "")>Administrator</!option>
        <!option value="Editor" @(post.admin_role == "Editor" ? "selected" : "")>Editor</!option>
        <!option value="Translator" @(post.admin_role == "Translator" ? "selected" : "")>Translator</!option>
    </select>

    @*Email*@
    <div class="annytab-form-label">Email</div>
    <input name="txtEmail" type="email" class="annytab-form-control" value="@post.admin_email" placeholder="my@email.com" required data-error-input="Bad input!" />

    @*Multiple emails*@
    <div class="annytab-form-label">Multiple emails</div>
    <input name="txtEmail" type="email" class="annytab-form-control" value="" placeholder="my@email.com, your@email.se" multiple required />

    @*Hidden field*@
    <div class="annytab-form-label">Hidden field</div>
    <input name="txtHidden" type="text" class="annytab-form-control" style="display:none;" value="ee" required data-error-required="Hidden field is required!" />
    <div class="validation-error" data-error-for="txtHidden"></div>

    @*Date*@
    <div class="annytab-form-label">Date</div>
    <input name="txtDate" type="date" class="annytab-form-control" value="" />

    @*Number*@
    <div class="annytab-form-label">Number</div>
    <input name="txtNumber" type="number" class="annytab-form-control" value="" min="1" max="10" />

    @*Range*@
    <div class="annytab-form-label">Range</div>
    <input name="txtRange" type="range" class="annytab-form-control" value="" min="1" max="10" step="1" />

    @*Pattern*@
    <div class="annytab-form-label">True/false</div>
    <input name="txtPattern" type="text" class="annytab-form-control" value="" pattern="^(?:tru|fals)e$" data-error-pattern="true or false only!" />

    @*Textarea*@
    <div class="annytab-form-label">Textarea</div>
    <textarea name="txtContents" required></textarea>

    <div class="annytab-basic-space"></div>

    @*Button panel*@
    <div class="annytab-form-button-container">
        <input type="button" class="annytab-form-button btn-disablable" value="@save_tt" onclick="sendForm(document.getElementById('inputForm'))" />
        @*<input type="submit" class="annytab-form-button" value="@save_tt" />*@
        <input type="button" class="annytab-form-button btn-disablable" value="@cancel_tt" onclick="location.href='/admin_administrators'" />
    </div>

</form>

@section scripts {
    <script>

        // Submit a form
        async function sendForm(form)
        {
            // Disable buttons
            disableButtons();

            // Make sure that the form is valid
            if (await annytab.validation.valid(form) === false) { enableButtons(); return false; }

            // Get form data
            var fd = new FormData(form);

            // Post form data
            var xhr = new XMLHttpRequest();
            xhr.open('POST', form.getAttribute('action'), true);
            xhr.onload = function () {
                if (xhr.status === 200)
                {
                    // Get the response
                    var data = JSON.parse(xhr.response);

                    // Check the success status
                    if (data.success === true)
                    {
                        // Output a success message
                        toastr['success'](data.message);
                    }
                    else
                    {
                        // Output error information
                        toastr['error'](data.message);
                    }
                }
                else
                {
                    // Output error information
                    toastr['error'](xhr.status + " - " + xhr.statusText);
                }

                // Enable buttons
                enableButtons();

            };
            xhr.onerror = function ()
            {
                // Output error information
                toastr['error'](xhr.status + " - " + xhr.statusText);

                // Enable buttons
                enableButtons();
            };
            xhr.send(fd);

        } // End of the sendForm method

        // Disable buttons
        function disableButtons()
        {
            var buttons = document.getElementsByClassName('btn-disablable');
            for (var i = 0; i < buttons.length; i++) {
                buttons[i].setAttribute('disabled', true);
            }

        } // End of the disableButtons method

        // Enable buttons
        function enableButtons()
        {
            var buttons = document.getElementsByClassName('btn-disablable');
            for (var i = 0; i < buttons.length; i++) {
                setTimeout(function (button) { button.removeAttribute('disabled'); }, 1000, buttons[i]);
            }

        } // End of the enableButtons method

    </script>
}

Styling

You can style error messages, apply styles to invalid and valid elements. This is an element that is used to output error messages for the txtUsername element.

<div class="validation-error" data-error-for="txtUsername"></div>

This is example CSS to style the error output element and to apply a style to invalid elements.

/* Validation */
.validation-error {
    display: block;
    font-weight: normal;
    font-size: 16px;
    line-height: 16px;
    color: #f00000;
    padding: 5px 5px 10px 0;
    margin: 0;
}
input:invalid, textarea:invalid{
    border: 1px solid #f00000;
}
/*input:valid, textarea:valid {
    border: 1px solid #4CAF50;
}*/

input:disabled, button:disabled, input:disabled:hover, button:disabled:hover {
    resize: none;
    color: #000000;
    background-color: #ddd;
    cursor: default;
}

A visual image of a form is displayed below, browers built-in styling is applied if a error message element not is present.

Html5 form validation

Remote validation

Remote validation means that we call a server method to get a true/false response. If you want to add remote validation you need to add a data-validation-remote attribute and a data-error-remote attribute to an element. The data-validation-remote attribute should include an url and names of additional fields, data is delimited by comma (,).

<input name="txtUsername" type="text" class="annytab-form-control" value="" data-validation-remote="/admin_administrators/verify_username,txtId" data-error-remote="The username is already in use!" />

You will also need a server method that is called by the validation code.

HttpPost]
[Authorize(Roles = "Administrator")]
public async Task<IActionResult> verify_username(IFormCollection collection)
{
    // Get the current domain
    WebDomain current_domain = await this.web_domain_repository.GetCurrentDomain(ControllerContext.HttpContext);

    // Get translated texts
    KeyStringList tt = await this.static_text_repository.GetFromCache(current_domain.back_end_language_code);

    // Get form data
    string id = collection["txtId"].ToString();
    string username = collection["txtUsername"].ToString();

    // Get a administrator on user name
    ModelItem<AdministratorDocument> admin_username_model = await this.administrator_repository.GetByUsername(username);

    // Check if the username exists already
    if (admin_username_model.item != null && id != admin_username_model.item.id)
    {
        // Return false
        return Ok(false);
        //return Json(data: false);
    }

    // Return success
    return Ok(true);
    //return Json(data: true);

} // End of the verify_username method

Confirmation validation

Confirmation validation (equalto) requires you to add a data-validation-equalto attribute and a data-error-equalto attribute to the element that is used to confirm another input element.

<input name="txtConfirmPassword" type="password" class="annytab-form-control" value="" data-validation-equalto="txtPassword" data-error-equalto="Passwords does not match!" />

File validation

File validation requires you to add a data-validation-file attribute with a maximum file size in bytes and a data-error-file attribute with an error message. Set the maximum file size to -1 if you only want to validate on file extensions. You can add an accept attribute to restrict upload to allowed file extensions only.

<div class="annytab-form-label">File</div>
<input type="file" accept=".jpg, .PNG" data-validation-file="262144" data-error-file="Max 256 KiB per file, must be .jpg or .png!" />

Leave a Reply

Your email address will not be published. Required fields are marked *