Anik Anik - 2 months ago 36
Javascript Question

How to apply conditional error messages?

I am trying to implement laravel's required_if validation in parsley, I was able to successfully apply it but main issue is coming while displaying error message. I have added following custom validator -

window.Parsley.addValidator('lpyRequiredIf', {
validateString(value, requirement) {
const fieldValue = document.getElementsByName(requirement[0])[0].value;
if (requirement.indexOf(fieldValue) > -1) {
return value !== '';
}
return true;
},
});


and my input looks like this -

<input class="form-control form-control-solid placeholder-no-fix" type="password" autocomplete="off" placeholder="Password" name="password" data-parsley-lpy-required-if="[&quot;email&quot;,&quot;anik@example.com&quot;,&quot;dan@example.com&quot;]" data-parsley-lpy-required-if-message="The password field is required when email address is :value." data-parsley-validate-if-empty="" data-parsley-whitespace="trim" data-parsley-lpy-custom-message="The password field is required when email address is :value.">


Now I want to show message exactly like it is shown in laravel validation.

This is what is shown -


The password field is required when email address is :value.


And I want to show -


The password field is required when email address is anik@example.com.


Can anyone suggest me how I can achieve this? Basically I want to replace :value with the email address which was entered if validation failed.

Answer

I figured it out how it can be done. I need to return jquery promise with first argument as custom message which I need to display -

window.Parsley.addValidator('lpyRequiredIf', {
    validateString(value, ...requirement) {
        let valid = true;
        const formElement = $(requirement[requirement.length - 1].parent.$element);
        const fieldToCheck = formElement.find(`[name= ${requirement[0]} ]`);
        if (fieldToCheck.length !== 0) {
            const fieldValue = fieldToCheck.val();
            const deferred = new $.Deferred();
            const baseErrorMessage = requirement[requirement.length - 1]
                                    .domOptions.lpyRequiredIfMessage;
            if (requirement.indexOf(fieldValue) > -1 && value === '') {
                deferred.reject(baseErrorMessage.replace(':value', fieldValue));
            } else {
                deferred.resolve();
            }
            valid = deferred.promise();
        }
        return valid;
    },
});

Here I am returning custom error message -

deferred.reject(baseErrorMessage.replace(':value', fieldValue));

P.S. - Code is bit edited from the question as I need it more refined.

Comments