0

For the Frontend i would like to have a simple Form Validation (client side first) including a dedicated error message. The Field validation has been written and its working:

document.addEventListener('DOMContentLoaded', function() {
    console.log('client-validation-age.js loaded');
    'use strict';
    if(document.formvalidator){
        console.log('client-validation-age.js active');
        document.formvalidator.setHandler('age', function(value) {
            const currentYear = new Date().getFullYear();
            const birthYear = new Date(value).getFullYear();
            const age = currentYear - birthYear;
            console.log('age', age);
            return age >= 5;
        });
    }
})

I've found this (I think outdated) answer here: How can I provide a custom message for a failed JFormRule validation?

From my understanding the response message should be placed into the JS code because its client side. How to return the error message too? I've already tried to return an object with the keys valid and message like so:

// Not working:
...
            if (age < 5) {
                return {
                    valid: false,
                    message: 'Age must be at least 5 years.'
                };
            }
...

Is it / how is it possible to set an individual message in the JS for client-side validation?

1 Answer 1

2

For static text use data-validation-text attribute:

<input name="test" class="form-validate validate-test" data-validation-text="Value is invalid">

In case you're using the Form API, use validationtext attribute in the field XML:

<field name="test" type="text" class="form-validate validate-test" validationtext="Value is invalid" />

If you need dynamic text based on value, there is no built-in support for this; validation handlers return only boolean value. You'd have to handle this yourself. One way is to change the data-validation-text attribute in the handler:

document.formvalidator.setHandler('test', function(value, element) {
    if (value.length < 5) {
        element.dataset.validationText = 'Username must be at least 5 characters';

        return false;
    }

    if (value.length > 20) {
        element.dataset.validationText = 'Username must be no more than 20 characters';

        return false;
    }

    return true;
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.