Skip to content

Commit

Permalink
style: minor refactor of #3726
Browse files Browse the repository at this point in the history
  • Loading branch information
logaretm committed Mar 20, 2022
1 parent 8db4077 commit a5b36f6
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 28 deletions.
46 changes: 18 additions & 28 deletions packages/vee-validate/src/validate.ts
Expand Up @@ -59,47 +59,37 @@ async function _validate(field: FieldValidationContext, value: unknown) {
return validateFieldWithYup(value, field.rules, { bails: field.bails });
}

// if a generic function, use it as the pipeline.
if (isCallable(field.rules)) {
// if a generic function or chain of generic functions
if (isCallable(field.rules) || Array.isArray(field.rules)) {
const ctx = {
field: field.name,
form: field.formData,
value: value,
};

const result = await field.rules(value, ctx);
const isValid = typeof result !== 'string' && result;
const message = typeof result === 'string' ? result : _generateFieldError(ctx);

return {
errors: !isValid ? [message] : [],
};
}

// chain of generic functions
if (Array.isArray(field.rules)) {
const ctx = {
field: field.name,
form: field.formData,
value: value,
};
const length = field.rules.length;
// Normalize the pipeline
const pipeline = Array.isArray(field.rules) ? field.rules : [field.rules];
const length = pipeline.length;
const errors: ReturnType<typeof _generateFieldError>[] = [];

for (let i = 0; i < length; i++) {
const rule = field.rules[i];
const rule = pipeline[i];
const result = await rule(value, ctx);
const isValid = typeof result !== 'string' && result;
if (isValid) {
continue;
}

const message = typeof result === 'string' ? result : _generateFieldError(ctx);
if (!isValid) {
if (field.bails) {
return {
errors: [message],
};
} else {
errors.push(message);
}
errors.push(message);

if (field.bails) {
return {
errors,
};
}
}

return {
errors,
};
Expand Down
1 change: 1 addition & 0 deletions packages/vee-validate/tests/useField.spec.ts
Expand Up @@ -374,6 +374,7 @@ describe('useField()', () => {
expect(meta1?.textContent).toBe('invalid');
expect(meta2?.textContent).toBe('invalid');
});

test('when bails is false', async () => {
mountWithHoc({
setup() {
Expand Down

0 comments on commit a5b36f6

Please sign in to comment.