Skip to content

Commit 7e79920

Browse files
authored
feat(validation): add to $errors if the validator has $message (#521)
1 parent b18b21d commit 7e79920

File tree

2 files changed

+30
-3
lines changed

2 files changed

+30
-3
lines changed

packages/vue-composable/__tests__/validation/validation.spec.ts

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -190,6 +190,30 @@ describe("validation", () => {
190190
]);
191191
});
192192

193+
it("should store $errors if $message is available", () => {
194+
const $message = "Invalid value";
195+
const v = useValidation({
196+
input: {
197+
$value: "",
198+
required: {
199+
$validator(x: string) {
200+
return false;
201+
},
202+
$message
203+
}
204+
},
205+
otherInput: {
206+
$value: "",
207+
required(x: string) {
208+
return false;
209+
}
210+
}
211+
});
212+
213+
expect(v.input.$errors).toMatchObject([$message]);
214+
expect(v.otherInput.$errors).toMatchObject([]);
215+
});
216+
193217
describe("render", () => {
194218
it("should show error", async () => {
195219
const required = (x: any) => !!x;

packages/vue-composable/src/validation/validation.ts

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -104,11 +104,12 @@ function isValidatorObject(v: any): v is ValidatorObject<any> {
104104
const buildValidationFunction = (
105105
r: Ref<any>,
106106
f: ValidatorFunc<any>,
107+
m: Ref<string | undefined>,
107108
handlers: Array<Function>
108109
) => {
109110
const $promise: Ref<Promise<boolean> | null> = ref(null);
110111
const $pending = ref(false);
111-
const $error = ref<Error>();
112+
const $error = ref<Error | string>();
112113
const $invalid = ref(false);
113114
let context: any = undefined;
114115

@@ -123,6 +124,7 @@ const buildValidationFunction = (
123124
} else {
124125
$invalid.value = !result;
125126
}
127+
$error.value = $invalid.value ? m.value : undefined;
126128
} catch (e) {
127129
$invalid.value = true;
128130
throw e;
@@ -169,11 +171,12 @@ const buildValidationValue = (
169171
): ValidatorResult & ValidatorResultPromise & ValidatorResultMessage => {
170172
const { $message, $validator, ...$rest } = isValidatorObject(v)
171173
? v
172-
: { $validator: v, $message: "" };
174+
: { $validator: v, $message: undefined };
173175

174176
const { $pending, $promise, $invalid, $error } = buildValidationFunction(
175177
r,
176178
$validator,
179+
ref($message),
177180
handlers
178181
);
179182

@@ -244,8 +247,8 @@ const buildValidation = <T>(
244247
$errors = computed(() =>
245248
validations
246249
.map(x => x.$error)
247-
.filter(Boolean)
248250
.map(x => unwrap(x))
251+
.filter(Boolean)
249252
);
250253
// $anyDirty = computed(() => validations.some(x => !!x));
251254
$anyInvalid = computed(() =>

0 commit comments

Comments
 (0)