Big thanks for this library!
I've got a use case where I want to validate a form field, but provide a different error message based on the criteria that fails.
For example, say I have a "Name" field that needs all of the following to validate:
And for each of those cases, I'd like to provide a specific error message:
My understanding is that I'd use a refinement to add the custom validation logic, but I'm struggling to figure out how to create conditional messages based on the criteria that fails. Ideally if more than one fails, I could return multiple messages.
Can anyone point me in the right direction? Would be happy to add an example to the repo once I've got it figured out!
In your use case I think that the easiest way would be to define a getValidationErrorMessage function (https://github.com/gcanti/tcomb-form-native#error-messages)
// predicates
var max20 = s => s.length <= 20;
var noemojis = s => s.indexOf('馃懄') === -1;
var Name = t.refinement(t.String, s => max20(s) && noemojis(s));
Name.getValidationErrorMessage = s => {
if (!s) {
return 'We need a name to proceed!';
}
if (!max20(s)) {
return 'The maximum character length is 20';
}
if (!noemojis(s)) {
return 'Sorry, we don\'t support emojis yet!';
}
};
var FormType = t.struct({
name: Name
});
@gcanti Perfect, thank you!
Most helpful comment
In your use case I think that the easiest way would be to define a
getValidationErrorMessagefunction (https://github.com/gcanti/tcomb-form-native#error-messages)