(baseRules: FormKitValidationRules = {})
| 184 | * @public |
| 185 | */ |
| 186 | export function createValidationPlugin(baseRules: FormKitValidationRules = {}) { |
| 187 | return function validationPlugin(node: FormKitNode): void { |
| 188 | let propRules = cloneAny(node.props.validationRules || {}) |
| 189 | let availableRules = { ...baseRules, ...propRules } |
| 190 | // create an observed node |
| 191 | const state = { input: token(), rerun: null, isPassing: true } |
| 192 | let validation = cloneAny(node.props.validation) |
| 193 | // If the node's validation props change, reboot: |
| 194 | node.on('prop:validation', ({ payload }) => reboot(payload, propRules)) |
| 195 | node.on('prop:validationRules', ({ payload }) => |
| 196 | reboot(validation, payload) |
| 197 | ) |
| 198 | /** |
| 199 | * Reboots the validation using new rules or declarations/intents. |
| 200 | * @param newValidation - New validation declaration to use |
| 201 | * @param newRules - New validation rules to use |
| 202 | * @returns |
| 203 | */ |
| 204 | function reboot( |
| 205 | newValidation: undefined | string | FormKitValidationIntent[], |
| 206 | newRules: FormKitValidationRules |
| 207 | ) { |
| 208 | if ( |
| 209 | eq(Object.keys(propRules || {}), Object.keys(newRules || {})) && |
| 210 | eq(validation, newValidation) |
| 211 | ) |
| 212 | return |
| 213 | propRules = cloneAny(newRules) |
| 214 | validation = cloneAny(newValidation) |
| 215 | availableRules = { ...baseRules, ...propRules } |
| 216 | // Destroy all observers that may re-trigger validation on an old stack |
| 217 | // Clear existing message observers |
| 218 | node.props.parsedRules?.forEach((validation: FormKitValidation) => { |
| 219 | removeMessage(validation) |
| 220 | removeListeners(validation.observer.receipts) |
| 221 | validation.observer.kill() |
| 222 | }) |
| 223 | // Remove all existing messages before re-validating |
| 224 | node.store.filter(() => false, 'validation') |
| 225 | node.props.parsedRules = parseRules(newValidation, availableRules, node) |
| 226 | state.isPassing = true |
| 227 | validate(node, node.props.parsedRules, state) |
| 228 | } |
| 229 | |
| 230 | // Validate the field when this plugin is initialized |
| 231 | node.props.parsedRules = parseRules(validation, availableRules, node) |
| 232 | validate(node, node.props.parsedRules, state) |
| 233 | } |
| 234 | } |
| 235 | |
| 236 | /** |
| 237 | * Given parsed validations, a value and a node, run the validations and set |
no test coverage detected