busypeoples / spected

Validation library
MIT License
703 stars 32 forks source link

Pass the field/key when errorMessage is a function #89

Closed Emilios1995 closed 7 years ago

Emilios1995 commented 7 years ago

It is very common to include the name of the field in the error message. I thought it convenient to include pass it when errorMessage is a function.

Here's how I'm using this feature (from my fork):

const isType = R.curry((type, field) => R.type(field) === type);
const typeMessage = (type, field) => `${field} has to be a ${type}`;
const typeRule = (type) => [
  isType(type),
  (val, field) => typeMessage(type, field)
];

const validationRules = {
  name: [typeRule("String")]
}
busypeoples commented 7 years ago

I like the approach, very nice example of how to create a [pred, errorMsg] tuple.

const typeRule = (type) => [
  isType(type),
  (val, field) => typeMessage(type, field)
];

Just so I fully understand, this:

const isType = R.curry((type, field) => R.type(field) === type);

should be:

const isType = R.curry((type, val) => R.type(val) === type);

right?

Emilios1995 commented 7 years ago

Exactly! Sorry, my bad.

busypeoples commented 7 years ago

Yes, I think this is very cool!

busypeoples commented 7 years ago

We should add this to the 0.6 release. Will probably merge this tomorrow. I also like the example

const validationRules = {
  name: [typeRule("String")]
}

shows how nicely one can create rules.

busypeoples commented 7 years ago

@Emilios1995 Great work!

Emilios1995 commented 7 years ago

Thanks, I'm glad you liked it!

Emilios1995 commented 7 years ago

We should also document this in the API docs. I'll probably make a commit for that later.

busypeoples commented 7 years ago

We should als add a test, but I can write that one tomorrow, if you have no time for that.

Emilios1995 commented 7 years ago

@busypeoples I'll try to do both things tonight. I'll ping you tomorrow if I have any trouble.

Emilios1995 commented 7 years ago

Done! But I'm not sure if I left that test too complex or the docs too verbose. What do you think?

P.S. I would also love to see something like my typeRule function somewhere in the readme, but I'll leave that to your consideration.

busypeoples commented 7 years ago

@Emilios1995 Thank you very much! I'll look into it in more detail in a couple of hours. But looks good after quickly going through the commits. I will merge later on today.

busypeoples commented 7 years ago

Regarding the typeRule, definitely. That example you have is more than elegant, and displays nicely how one can compose rules to bigger rules etc.