Skip to content

Add mask option to filter object with constraint structure #60

@ricardogama

Description

@ricardogama

The possibility of returning the validated object masked with the constraint keys instead of true seems a powerful feature, that would allow filtering undesired properties from incoming data.

Doing so without breaking changes would require adding a 4th argument to validate, but this approach seems very verbose and weird to use (or implement an handle) when using one of the optional arguments without the other:

// using both options
Validator.validate({ foo: 'bar' }, { foo: [is('bar').equalTo('bar'), is('biz').equalTo('biz')] }, 'bar', true);

// using `mask` without `group`
Validator.validate({ foo: 'bar' }, { foo: [is('bar').equalTo('bar'), is('biz').equalTo('biz')] }, undefined, true)

Since following this solution can cause the argument number to scale as new options arise, I suggest to update the last argument to an options object, where both group and mask options can be included:

Validator.validate({ foo: 'bar' }, { foo: [is('bar').equalTo('bar'), is('biz').equalTo('biz')] },  {
  group: 'bar',
  mask: true
});

The mask option would then produce the following result:

const data = {
  foo: { bar: 'biz', qux: 'qix' }, 
  baz: 'bez' 
};

const constraint = {
  foo: { bar: is.required() }
};

const unmasked = Validator.validate(data, constraint);

console.log(unmasked);
// -> true

const masked = Validator.validate(data, constraint, {
  mask: true
});

console.log(masked);
// -> { foo: { bar: 'biz' } }

This is a breaking change but I think that besides adding this powerful masking feature it will bring benefits when implementing new options in the future.

@guillaumepotier @fixe @ruimarinho WDYT?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions