mobx-react-form
mobx-react-form copied to clipboard
Allow custom messages for DVR on a per-field basis
https://github.com/skaterdav85/validatorjs#custom-error-messages
From their readme:
"""
You can even provide error messages on a per attribute basis! Just set the message's key to 'validator.attribute'
let input = { name: '', email: '' };
let rules = { name : 'required', email : 'required' };
let validation = new Validator(input, rules, {
"required.email": "Without an :attribute we can't reach you!"
});
validation.errors.first('name'); // returns 'The name field is required.'
validation.errors.first('email'); // returns 'Without an email we can\'t reach you!'
"""
Related code in DVR.js file:
validateFieldSync(field, form, data) {
const $rules = this.rules(field.rules, 'sync');
// exit if no rules found
if (_.isEmpty($rules[0])) return;
// get field rules
const rules = { [field.path]: $rules };
// create the validator instance
const Validator = this.validator;
const validation = new Validator(data, rules);
// set label into errors messages instead key
validation.setAttributeNames({ [field.path]: field.label });
// check validation
if (validation.passes()) return;
// the validation is failed, set the field error
field.invalidate(_.first(validation.errors.get(field.path)));
}
The particular section is new Validator(data, rules)
can you explain the code and what needs to be changed? Thanks.
related #368
@Dakkers do you have any updates or how'd you solve this issue?
@andrefox333 we just use validators
instead of rules
for everywhere we need a custom error message 🤷♂ not a real solution since it kinda defeats the purpose of using validatorjs at all.
@Dakkers thanks, are you able to provide a small example of what you mean by using validators instead of rules?
I use DVR throughout my app for multiple forms. Recently the need came for custom error message in one of the fields. It will be highly appreciated if there is a way by which I can add it without refactoring DVR out of the forms.
@andrefox333 here's an example of a field:
{
name: 'company_name',
type: 'text',
validators: [
({ field }) => {
return [
!!field.value,
'Name is incomplete.'
];
}
],
value: ''
}
@Dakkers thanks so much. I'm running DVR at the moment, but needing to initialize VJF for that snippet you shared to work.
@foxhound87 is it weird / anti-pattern to run both validation types?
@andrefox333 I've had success with using both, though typically I opt in favour of validators
for i18n. that being said, I don't use both rules
and validators
in the same field - different fields in the same form.
@andrefox333 you can use any validators at a time, they will be executed in the order you defined them in the plugins
object.