registerValidator()

Register a validator

It is used when you want to use a custom validator.

registerValidator(name: String, func: Function): Core

* presents a required parameter

  • name * — The name of validator
  • func * — The validator function

Example: Preventing user to have same value as the placeholder

For instance, we could show an error message when someone enters First name or Last name for the text fields named firstName and lastName, respectively.

To do that, we create a custom validator following the signature as below:


const checkPlaceholder = function() {
    return {
        validate: function(input) {
            // input.element presents the field element
            // input.elements presents all field elements
            // input.field is the field name
            // input.value is the field value

            // Has to return an object containing valid key
            return {
                valid: input.value != input.element.getAttribute('placeholder'),
            };
        },
    };
};

Now, you can apply the created validator with multiple fields:


FormValidation
    .formValidation(
        document.getElementById('demoForm'),
        {
            fields: {
                firstName: {
                    validators: {
                        ...
                        placeholder: {
                            message: 'The value cannot be the same as placeholder'
                        },
                    }
                },
                lastName: {
                    validators: {
                        ...
                        placeholder: {
                            message: 'The value cannot be the same as placeholder'
                        },
                    }
                },
            },
            plugins: {
                ...
            },
        }
    )
    .registerValidator('placeholder', checkPlaceholder);

For this specific requirement, we also can use the callback validator:


callback: {
    message: 'The value cannot be the same as placeholder',
    callback: function(input) {
        return {
            valid: input.value != input.element.getAttribute('placeholder'),
        };
    },
}