Fp-ts: Help with Validation module

Created on 17 Sep 2018  路  3Comments  路  Source: gcanti/fp-ts

(Please let me know if this is not allowed here)

I'm still learning all this stuff, so please bear with me.

I took a look at the Validation module and while I understand how it's currently working, I don't quite get how to add more validation rules to the applicative.

If, for example, after validateAge you wanted to add validateOldEnough and ensure the person was over 21, how would you add that to the validatePerson function?

Most helpful comment

You can use getMonad instead of getApplicative. You can either chain another validation after validatePerson

const A = getMonad(getSemigroup<string>())

const validateOldEnough = (age: number): Validation<NonEmptyArray<string>, number> =>
  age >= 21 ? success(age) : failure(new NonEmptyArray('Invalid age: not old enough', []))

console.log(A.chain(validatePerson({ name: 'Giulio', age: '18' }), p => validateOldEnough(p.age).map(_ => p)))
// failure(new NonEmptyArray("Invalid age: not old enough", []))

or chain another validation after validateAge

function validatePerson2(input: Record<string, string>): Validation<NonEmptyArray<string>, Person> {
  return A.ap(validateName(input['name']).map(person), A.chain(validateAge(input['age']), validateOldEnough))
}

console.log(validatePerson2({ name: 'Giulio', age: '18' }))
// failure(new NonEmptyArray("Invalid age: not old enough", []))

All 3 comments

You can use getMonad instead of getApplicative. You can either chain another validation after validatePerson

const A = getMonad(getSemigroup<string>())

const validateOldEnough = (age: number): Validation<NonEmptyArray<string>, number> =>
  age >= 21 ? success(age) : failure(new NonEmptyArray('Invalid age: not old enough', []))

console.log(A.chain(validatePerson({ name: 'Giulio', age: '18' }), p => validateOldEnough(p.age).map(_ => p)))
// failure(new NonEmptyArray("Invalid age: not old enough", []))

or chain another validation after validateAge

function validatePerson2(input: Record<string, string>): Validation<NonEmptyArray<string>, Person> {
  return A.ap(validateName(input['name']).map(person), A.chain(validateAge(input['age']), validateOldEnough))
}

console.log(validatePerson2({ name: 'Giulio', age: '18' }))
// failure(new NonEmptyArray("Invalid age: not old enough", []))

Thank you!

@mattgrande You can also take a look at tests, here and here

Was this page helpful?
0 / 5 - 0 ratings

Related issues

vicrac picture vicrac  路  4Comments

FruitieX picture FruitieX  路  3Comments

Crashthatch picture Crashthatch  路  4Comments

mmkal picture mmkal  路  3Comments

maciejsikora picture maciejsikora  路  3Comments