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

Unable to set a custom validation on two or more fields

Open hugoruscitti opened this issue 7 years ago • 4 comments

Hi!, i can't make a customValidator that check two fields in the changeset. The current changeset is hidden from validator for any reason, or simply i don't find a way go get it?

I think my usercase isn't very strange, i have to date and time fields that needs to be coherent between them.

hugoruscitti avatar Sep 10 '17 04:09 hugoruscitti

@hugoruscitti did you make any progress on this issue? I am facing the problem right now, with two date fields that are collectively only valid if the first is earlier than the second. I've made some progress, by using the changes and content parameters passed into the custom validation routine. For example,

// validators/custom.js
export default function validateLessThanAttr(largerAttrName = '') {
  return (key, newValue, oldValue, changes, content) => {
    const largerValue = Ember.get(changes, largerAttrName) || Ember.get(content, largerAttrName);
    return parseInt(newValue) < parseInt(largerValue) || `Must be less than ${largerValue}`;
  }
}

Here's a twiddle showing it in action. If you leave the larger number at its default, or set it to something new, and then change the smaller number to be greater than or equal to that, a validation error will appear. The logic would be very similar for dates of course, but with parsing via moment first, or however else you are dealing with them.

There is still one main problem with it that I'd like to find a way to address: A validation error on the smaller number isn't cleared if the larger number is changed to make a valid combination.

For example, if larger is 10 and smaller is 15, then the validation error on smaller will say "Must be less than 10". If I then change larger to be 20, the error message will still be there, saying that smaller has to be less than the old value of 10. (This is another example of #152.)

mikeu avatar Oct 05 '17 14:10 mikeu

I've run into this as well, it seems like its currently not possible to have a custom validator whose rules are dependent on the current values of other properties in the changeset (that have NOT yet been applied to the target object).

It seems like maybe in addition to the content param (which is the underlying target object), the validators should be receiving another param, the changeset?

billdami avatar Oct 18 '17 16:10 billdami

@billdami isn't that exactly what the changes parameter in the example and twiddle above gives you?

mikeu avatar Oct 18 '17 17:10 mikeu

@mikeu you know what you're absolutely right. :D When I was originally trying to use the changes object for this, I was incorrectly testing for a truthy value, when in my case I should be just seeing if the changes object contains the property, even if its false.

billdami avatar Oct 18 '17 17:10 billdami