Created
May 10, 2020 06:27
-
-
Save allthesignals/ab854625ab0a2e5ea5aed475e2f74456 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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