Skip to content

Commit

Permalink
feat(validation): add to $errors if the validator has $message (#521)
Browse files Browse the repository at this point in the history
  • Loading branch information
pikax committed Aug 15, 2020
1 parent b18b21d commit 7e79920
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 3 deletions.
24 changes: 24 additions & 0 deletions packages/vue-composable/__tests__/validation/validation.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,30 @@ describe("validation", () => {
]);
});

it("should store $errors if $message is available", () => {
const $message = "Invalid value";
const v = useValidation({
input: {
$value: "",
required: {
$validator(x: string) {
return false;
},
$message
}
},
otherInput: {
$value: "",
required(x: string) {
return false;
}
}
});

expect(v.input.$errors).toMatchObject([$message]);
expect(v.otherInput.$errors).toMatchObject([]);
});

describe("render", () => {
it("should show error", async () => {
const required = (x: any) => !!x;
Expand Down
9 changes: 6 additions & 3 deletions packages/vue-composable/src/validation/validation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,11 +104,12 @@ function isValidatorObject(v: any): v is ValidatorObject<any> {
const buildValidationFunction = (
r: Ref<any>,
f: ValidatorFunc<any>,
m: Ref<string | undefined>,
handlers: Array<Function>
) => {
const $promise: Ref<Promise<boolean> | null> = ref(null);
const $pending = ref(false);
const $error = ref<Error>();
const $error = ref<Error | string>();
const $invalid = ref(false);
let context: any = undefined;

Expand All @@ -123,6 +124,7 @@ const buildValidationFunction = (
} else {
$invalid.value = !result;
}
$error.value = $invalid.value ? m.value : undefined;
} catch (e) {
$invalid.value = true;
throw e;
Expand Down Expand Up @@ -169,11 +171,12 @@ const buildValidationValue = (
): ValidatorResult & ValidatorResultPromise & ValidatorResultMessage => {
const { $message, $validator, ...$rest } = isValidatorObject(v)
? v
: { $validator: v, $message: "" };
: { $validator: v, $message: undefined };

const { $pending, $promise, $invalid, $error } = buildValidationFunction(
r,
$validator,
ref($message),
handlers
);

Expand Down Expand Up @@ -244,8 +247,8 @@ const buildValidation = <T>(
$errors = computed(() =>
validations
.map(x => x.$error)
.filter(Boolean)
.map(x => unwrap(x))
.filter(Boolean)
);
// $anyDirty = computed(() => validations.some(x => !!x));
$anyInvalid = computed(() =>
Expand Down

0 comments on commit 7e79920

Please sign in to comment.