Fonk Doc
1. General
2. Validators
ValidatorsBuilt in validatorsThird Party validatorsCustom validators synchronousCustom validators asynchronous
3. Messages
4. Form Libraries
5. API
6. Posts

Validators

Fonk isolated field and record validation into Validators

A validator is a function, that given an input (for instance, field name, fieldvalue), check for a give business rule (e.g. is field a valid email, or has been field informed), and depending on the success or not of that validation it returns a succeed output, or a fail one (including additional context information like the error message or validation type applied).

For instance let's create a validator that check if a field contains no blank spaces:

const VALIDATOR_TYPE = 'NO_SPACES';
let defaultMessage = 'String cannot contain white spaces';
export const setErrorMessage = message => (defaultMessage = message);
export const validator = (fieldValidatorArgs) => {
const {
value,
// Just if we want to override the default error message
message = defaultMessage,
} = fieldValidatorArgs;
// If the field is not informed, just return succeeded, this
// case should be handle before by the required validator
const succeeded = !value || (typeof value === 'string' && value === value.trim());
// Return ValidationResultStructure
// ValidationSucceeded: true / false
// message: error message (string) can be overriden
// type: type of validation executed (in this case NO_SPACES)
// In this case we directly return data (sync validator),
// we can return promises as well (async validator)
return {
succeeded,
message: succeeded ? '' : (message as string),
type: VALIDATOR_TYPE,
};
}

You can use typescript to build this validator, validators typings definitions are exposed by the library.

What are the advantage of Validators?

  • We just isolates validation in a single function.
  • These functions can be easily reused.
  • These functions be easily tested.
  • These functions do one thing and only one thing.
  • We can create microlibraries for validators and cherry pick the ones that we really need in our project.

Validators can be:

  • Synchronous.
  • Asynchronous.

Validators can be defined:

  • At field level.
  • At record level.

You can find:

  • A set of built-in validators in the core Fonk library (required, minLength, maxLength, pattern, email).
  • A list of microlibraries available with a range set of validators already implemented (just install the ones that you need, like a buffet style).
  • If any of the built-in validators doesn't match your needs, you can build your own custom validator, and even publish it as a microlibrary to spread the OSS love around the world.

Enough theory, let's get started learning how to use the validators that already ships Fonk library, click on this link to get started.