Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add email validation to a field with tcomb-form-native?

Using the tcomb-form-native library with react native - I've set the keyboardType to email-address. How do I add a regex or email validator to the form? Do I have to do it on the submit function (and throw a special error?) or is there a regex validation field I can set using the library?

I noticed that the tcomb-validation https://github.com/gcanti/tcomb-validationlibrary has a RegExp type field - but I don't see any examples of how to use it. The example shown seems to test if a field is a regex pattern, which is a confusing use case, because you would normally want to test a field against a regex pattern, not enter a regex pattern into a field.

like image 549
MonkeyBonkey Avatar asked May 01 '17 19:05

MonkeyBonkey


1 Answers

You can create your own subtype with RegExp check

const Email = t.refinement(t.String, email => {
  const reg = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/; //or any other regexp
  return reg.test(email);
});

const Person = t.struct({
  name: t.String,
  email: Email,
});
like image 160
magneticz Avatar answered Oct 21 '22 14:10

magneticz