ember-changeset-validations icon indicating copy to clipboard operation
ember-changeset-validations copied to clipboard

Feature request - sequential validations

Open lindyhopchris opened this issue 4 years ago • 8 comments

Using #220 as inspiration, I'm frequently using this custom validator in my code:

export default function validateChain(validators) {
  return async (key, value, oldValue, changes, content) => {
    let result;
    let index = 0;

    do {
      let validator = validators[index++];
      result = await validator(key, value, oldValue, changes, content);
    } while (true === result && index < validators.length);

    return result;
  };
}

My use case is exactly the same as the linked issue - I have expensive async custom validators that there's no point calling if other validators fail. Example use case:

import {
  validatePresence,
  validateFormat
} from 'ember-changeset-validations/validators';
import validateChain from '../validators/chain';
import validateUniqueEmail from '../validators/unique-email';

export default {
  email: validateChain([
    validatePresence(true),
    validateFormat({ type: 'email' }),
    validateUniqueEmail(),
  ]),
};

I think this sequential validator is really useful as this use case is common. So my question is - would you accept a PR adding it to this package?

If yes, then two questions:

  1. What would you like the validator to be called?
  2. How should I be checking for object validators? Just checking for the existence of a validate function?

lindyhopchris avatar Jan 15 '21 15:01 lindyhopchris

I have exactly the same issue - +1 for me

BryanCrotaz avatar Feb 09 '21 13:02 BryanCrotaz

Are your expensive validators server-side? If so how are you dealing with authentication without access to services?

BryanCrotaz avatar Feb 09 '21 13:02 BryanCrotaz

Maybe a better fix would be a default feature to run all sync validators first and only run async validators if the sync ones all pass?

BryanCrotaz avatar Feb 09 '21 13:02 BryanCrotaz

@BryanCrotaz I'm using fetch for the async validators, and have utility functions to configure the fetch to work with the server. Luckily it works without a service: it would be better implemented if I could use a service.

lindyhopchris avatar Feb 09 '21 16:02 lindyhopchris

@lindyhopchris That would be a great addition to this library. Perhaps exported from validators/index.

snewcomer avatar Feb 10 '21 01:02 snewcomer

@snewcomer great, I'll put together a PR. Hopefully I should have some open source time this coming week to sort it out.

lindyhopchris avatar Feb 14 '21 11:02 lindyhopchris

@lindyhopchris Lmk if this is something you still want to take on! Happy to do it if you are busy.

snewcomer avatar Feb 28 '21 13:02 snewcomer

@snewcomer I am still happy to do it, but not sure quite when I can get to it. Possibly this week.

lindyhopchris avatar Feb 28 '21 14:02 lindyhopchris