Tcomb-form-native: Conditional Validation Error Messages

Created on 23 Feb 2016  路  2Comments  路  Source: gcanti/tcomb-form-native

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:

  • Max Length
  • No Emojis
  • Isn't Blank

And for each of those cases, I'd like to provide a specific error message:

  • "The maximum character length is 20"
  • "Sorry, we don't support emojis yet!"
  • "We need a name to proceed!"

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!

Code Examples Question

Most helpful comment

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
});

All 2 comments

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!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

pgmemk picture pgmemk  路  4Comments

abdelghafourzguindou picture abdelghafourzguindou  路  4Comments

alexicum picture alexicum  路  6Comments

scarlac picture scarlac  路  4Comments

pocesar picture pocesar  路  4Comments