Skip to content

Instantly share code, notes, and snippets.

@allthesignals
Created May 10, 2020 06:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save allthesignals/ab854625ab0a2e5ea5aed475e2f74456 to your computer and use it in GitHub Desktop.
Save allthesignals/ab854625ab0a2e5ea5aed475e2f74456 to your computer and use it in GitHub Desktop.
import buildMessage from 'ember-changeset-validations/utils/validation-errors';
import { validate } from 'ember-validators';
export default function validatePresence(options) {
let targets;
if (typeof options === 'boolean') {
options = { presence: options };
} else if (options && options.on !== undefined) {
if (typeof options.on === 'string') {
targets = [options.on];
} else if (Array.isArray(options.on)) {
targets = options.on;
}
delete options.on;
}
return (key, value, _oldValue, changes, content) => {
const hasTargetValues = targets.some((target) => changes[target] || (changes[target] === undefined && content[target]));
const hasMatchingWith = options.withValue && targets.some((target) => (changes[target] || content[target]) === options.withValue);
// if it targets are empty, this is valid because
// it's only required (validates presence) when targets
// are filled
if ((targets && !hasTargetValues) || !hasMatchingWith) {
return true;
}
const result = validate('presence', value, options, null, key);
if (typeof result === 'boolean' || typeof result === 'string') {
return result;
}
// We flipped the meaning behind `present` and `blank` so switch the two
if (result.type === 'present') {
result.type = 'blank';
} else if (result.type === 'blank') {
result.type = 'present';
}
return buildMessage(key, result);
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment