gcanti / tcomb-validation

Validation library based on type combinators
MIT License
400 stars 23 forks source link

Struct with predicate #51

Open jojolapin972 opened 7 years ago

jojolapin972 commented 7 years ago

I am using version 3.2.2 and I am trying to build a library of reusable validators around tcomb-validator.

So I first defined my custom field validators which are predicates and then wanted to compose an object validator using the structure like follow:

       ` var Title = function (s) {
              return s.length > 2 && s.length <= 255;
        }`

        `Title.getValidationErrorMessage = function (value) {
            if (!value) {
                return 'document.validation.error.missing';
            }

            if (value.length <= 2) {
                return 'document.validation.error.tooShort';
            }

            if (payload.title.length > 255) {
                return 'document.validation.error.tooLong';
            }
        };`

And then used like this:

        `var BaseDocument = t.struct({
            title: Title,
            body: OtherCustomType,
        });
        var payload = {
            title: "abcd",
            body: "some other valid value",
        };
        var validationResult = validate(payload, BaseDocument);`

But in this case, even if the payload is valid and the validationResult.isValid() returns true