revalidateField()

Revalidate a particular field

revalidateField(field: String): Promise

* presents a required parameter

  • field * — The field name

This method is useful when the field value is effected by third parties (for example, attach another UI library to the field).

Since there isn't an automatic way for FormValidation to know when the field value is modified in those cases, we need to revalidate the field manually.


fv
    .revalidateField('userName')
    .then(function(status) {
        // status can be one of the following value
        // 'NotValidated' or FormValidation.Status.NotValidated: The field is not yet validated
        // 'Valid' or FormValidation.Status.Valid: The field is valid
        // 'Invalid' or FormValidation.Status.Invalid: The field is invalid
        ...
    });

Look at the Integration page to see more examples.

Example: Validating multiple inputs as one

In some cases, you need to validate a value which is combined by various fields. For instance, a Birthday field might be a combination of Date, Month and Year one.

This example show a way to deal with these cases. The following form requires all of Date, Month and Year fields. Also, the combination of them must be a valid date.

First, we need to create a hidden field that its value is generated from Date, Month and Year fields:


We set the validator rules for that hidden field as usual:


const form = document.getElementById('demoForm');

const fv = FormValidation.formValidation(
    form,
    {
        fields: {
            dob: {
                validators: {
                    notEmpty: {
                        message: 'Please fill out each field'
                    },
                    date: {
                        format: 'YYYY/MM/DD',
                        message: 'Please enter a valid date',
                    },
                }
            }
        },
        plugins: {
            ...
        },
    }
);

Finally, when any of Date, Month and Year fields changes its value, we need to update the hidden field value and revalidate it using the revalidateField() method:


const keyupHandler = function() {
    const y = form.querySelector('[name="year"]').value;
    const m = form.querySelector('[name="month"]').value;
    const d = form.querySelector('[name="date"]').value;

    // Set the dob field value
    const dob = y === '' || m === '' || d === '' ? '' : [y, m, d].join('/');
    form.querySelector('[name="dob"]').value = dob;

    // Revalidate it
    fv.revalidateField('dob');
};

form.querySelector('[name="year"]').addEventListener('keyup', keyupHandler);
form.querySelector('[name="month"]').addEventListener('keyup', keyupHandler);
form.querySelector('[name="date"]').addEventListener('keyup', keyupHandler);

Here is the working example: