Skip to content

Commit 70975ec

Browse files
author
Martynas Žilinskas
committed
Fixed validation.
1 parent ec606d0 commit 70975ec

File tree

1 file changed

+45
-19
lines changed

1 file changed

+45
-19
lines changed
Lines changed: 45 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,53 @@
11
import { FieldValue } from "simplr-forms/contracts";
2-
import { ProcessValue } from "simplr-forms/utils";
2+
import {
3+
ProcessValue,
4+
IsComponentOfType,
5+
RenderComponents,
6+
ConstructFormError
7+
} from "simplr-forms/utils";
38

4-
import { Validator, FIELD_VALIDATOR_FUNCTION_NAME, FORM_VALIDATOR_FUNCTION_NAME } from "../contracts";
9+
import {
10+
Validator,
11+
FIELD_VALIDATOR_FUNCTION_NAME,
12+
FORM_VALIDATOR_FUNCTION_NAME
13+
} from "../contracts";
514

615

16+
function IsPromise<T>(value: any): value is Promise<T> {
17+
return value != null && value.then != null && value.catch != null;
18+
}
19+
20+
export async function ValidateValue(
21+
components: Array<JSX.Element>,
22+
value: any,
23+
validatorTypeFunctionName: string) {
24+
const validators = components.filter(x => IsComponentOfType(x, validatorTypeFunctionName));
25+
const renderedValidators = RenderComponents<Validator>(validators);
26+
27+
for (const validator of renderedValidators) {
28+
const validationResult = validator.Validate(value);
29+
// Ensure that we have a promise
30+
let promise: Promise<void>;
31+
if (IsPromise<void>(validationResult)) {
32+
promise = validationResult;
33+
} else {
34+
promise = new Promise<void>((resolve, reject) => {
35+
const error = ConstructFormError(validationResult);
36+
if (error !== undefined) {
37+
reject(validationResult);
38+
return;
39+
}
40+
resolve();
41+
});
42+
}
43+
await promise;
44+
}
45+
}
46+
747
export function ValidateField(components: Array<JSX.Element>, value: FieldValue) {
8-
return ProcessValue<Validator, Promise<void>>(components, value, FIELD_VALIDATOR_FUNCTION_NAME,
9-
async (processor, value) => {
10-
const validationResult = processor.Validate(value);
11-
if (validationResult != null && typeof validationResult === "string") {
12-
throw validationResult;
13-
}
14-
return await validationResult;
15-
});
48+
return ValidateValue(components, value, FIELD_VALIDATOR_FUNCTION_NAME);
1649
}
1750

18-
export function ValidateForm(components: Array<JSX.Element>, value: FieldValue) {
19-
return ProcessValue<Validator, Promise<void>>(components, value, FORM_VALIDATOR_FUNCTION_NAME,
20-
async (processor, value) => {
21-
const validationResult = processor.Validate(value);
22-
if (validationResult != null && typeof validationResult === "string") {
23-
throw validationResult;
24-
}
25-
return await validationResult;
26-
});
51+
export function ValidateForm(components: Array<JSX.Element>, value: any) {
52+
return ValidateValue(components, value, FORM_VALIDATOR_FUNCTION_NAME);
2753
}

0 commit comments

Comments
 (0)