Refactor useFormValidation
This commit is contained in:
parent
b42bf24935
commit
82ffa801d6
@ -1,5 +1,5 @@
|
||||
import "keycloakify/tools/Array.prototype.every";
|
||||
import { useMemo, useReducer, Fragment } from "react";
|
||||
import { useMemo, useReducer, Fragment, type Dispatch } from "react";
|
||||
import { id } from "tsafe/id";
|
||||
import type { MessageKey } from "keycloakify/login/i18n/i18n";
|
||||
import type { Attribute, Validators } from "keycloakify/login/kcContext/KcContext";
|
||||
@ -7,12 +7,46 @@ import { useConstCallback } from "keycloakify/tools/useConstCallback";
|
||||
import { emailRegexp } from "keycloakify/tools/emailRegExp";
|
||||
import type { KcContext } from "../kcContext";
|
||||
import type { I18n } from "../i18n";
|
||||
import type { Param0 } from "tsafe";
|
||||
import { assert, type Equals } from "tsafe/assert";
|
||||
|
||||
/**
|
||||
* NOTE: The attributesWithPassword returned is actually augmented with
|
||||
* artificial password related attributes only if kcContext.passwordRequired === true
|
||||
*/
|
||||
export function useFormValidation(params: {
|
||||
export type FormFieldError = {
|
||||
errorMessage: JSX.Element;
|
||||
errorMessageStr: string;
|
||||
validatorName: keyof Validators | undefined;
|
||||
};
|
||||
|
||||
export type FormFieldState = {
|
||||
name: string;
|
||||
/** The index is always 0 for non multi-valued fields */
|
||||
index: number;
|
||||
value: string;
|
||||
displayableError: FormFieldError[];
|
||||
};
|
||||
|
||||
export type FormState = {
|
||||
isFormSubmittable: boolean;
|
||||
formFieldStates: FormFieldState[];
|
||||
};
|
||||
|
||||
export type FormAction =
|
||||
| {
|
||||
action: "update value";
|
||||
name: string;
|
||||
index: number;
|
||||
newValue: string;
|
||||
}
|
||||
| {
|
||||
action: "focus lost";
|
||||
name: string;
|
||||
index: number;
|
||||
}
|
||||
| {
|
||||
action: "add value to multi-valued attribute";
|
||||
name: string;
|
||||
};
|
||||
|
||||
export type ParamsOfUseFromValidation = {
|
||||
kcContext: {
|
||||
messagesPerField: Pick<KcContext.Common["messagesPerField"], "existsError" | "get">;
|
||||
profile: {
|
||||
@ -22,26 +56,38 @@ export function useFormValidation(params: {
|
||||
realm: { registrationEmailAsUsername: boolean };
|
||||
};
|
||||
passwordValidators?: Validators;
|
||||
//TODO: Add a param that enable not to use password confirmation
|
||||
requirePasswordConfirmation?: boolean;
|
||||
i18n: I18n;
|
||||
}) {
|
||||
const { kcContext, passwordValidators = {}, i18n } = params;
|
||||
};
|
||||
|
||||
const attributesWithPassword = useMemo(
|
||||
() =>
|
||||
!kcContext.passwordRequired
|
||||
? kcContext.profile.attributes
|
||||
: (() => {
|
||||
const name = kcContext.realm.registrationEmailAsUsername ? "email" : "username";
|
||||
export type ReturnTypeOfUseFormValidation = {
|
||||
formState: FormState;
|
||||
dispatchFormAction: Dispatch<FormAction>;
|
||||
attributesWithPassword: Attribute[];
|
||||
};
|
||||
|
||||
return kcContext.profile.attributes.reduce<Attribute[]>(
|
||||
(prev, curr) => [
|
||||
...prev,
|
||||
...(curr.name !== name
|
||||
? [curr]
|
||||
: [
|
||||
curr,
|
||||
id<Attribute>({
|
||||
/**
|
||||
* NOTE: The attributesWithPassword returned is actually augmented with
|
||||
* artificial password related attributes only if kcContext.passwordRequired === true
|
||||
*/
|
||||
export function useFormValidation(params: ParamsOfUseFromValidation): ReturnTypeOfUseFormValidation {
|
||||
const { kcContext, passwordValidators = {}, requirePasswordConfirmation = true, i18n } = params;
|
||||
|
||||
const attributesWithPassword = useMemo(() => {
|
||||
const attributesWithPassword: Attribute[] = [];
|
||||
|
||||
for (const attribute of kcContext.profile.attributes) {
|
||||
attributesWithPassword.push(attribute);
|
||||
|
||||
add_password_and_password_confirm: {
|
||||
if (attribute.name !== (kcContext.realm.registrationEmailAsUsername ? "email" : "username")) {
|
||||
// NOTE: We want to add password and password-confirm after the field that identifies the user.
|
||||
// It's either email or username.
|
||||
break add_password_and_password_confirm;
|
||||
}
|
||||
|
||||
attributesWithPassword.push(
|
||||
{
|
||||
"name": "password",
|
||||
"displayName": id<`\${${MessageKey}}`>("${password}"),
|
||||
"required": true,
|
||||
@ -52,8 +98,8 @@ export function useFormValidation(params: {
|
||||
"html5DataAnnotations": {},
|
||||
// NOTE: Compat with Keycloak version prior to 24
|
||||
...({ "groupAnnotations": {} } as {})
|
||||
}),
|
||||
id<Attribute>({
|
||||
},
|
||||
{
|
||||
"name": "password-confirm",
|
||||
"displayName": id<`\${${MessageKey}}`>("${passwordConfirm}"),
|
||||
"required": true,
|
||||
@ -69,112 +115,135 @@ export function useFormValidation(params: {
|
||||
"annotations": {},
|
||||
"html5DataAnnotations": {},
|
||||
"autocomplete": "new-password",
|
||||
"hidden": !requirePasswordConfirmation,
|
||||
// NOTE: Compat with Keycloak version prior to 24
|
||||
...({ "groupAnnotations": {} } as {})
|
||||
})
|
||||
])
|
||||
],
|
||||
[]
|
||||
);
|
||||
})(),
|
||||
[kcContext, JSON.stringify(passwordValidators)]
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return attributesWithPassword;
|
||||
}, []);
|
||||
|
||||
const { getErrors } = useGetErrors({
|
||||
"kcContext": {
|
||||
"messagesPerField": kcContext.messagesPerField,
|
||||
"profile": {
|
||||
"attributes": attributesWithPassword
|
||||
}
|
||||
},
|
||||
kcContext,
|
||||
"attributes": attributesWithPassword,
|
||||
i18n
|
||||
});
|
||||
|
||||
const initialInternalState = useMemo(
|
||||
() =>
|
||||
Object.fromEntries(
|
||||
attributesWithPassword
|
||||
.map(attribute => ({
|
||||
attribute,
|
||||
"errors": getErrors({
|
||||
"name": attribute.name,
|
||||
"fieldValueByAttributeName": Object.fromEntries(
|
||||
attributesWithPassword.map(({ name, value }) => [name, { "value": value ?? "" }])
|
||||
)
|
||||
})
|
||||
}))
|
||||
.map(({ attribute, errors }) => [
|
||||
attribute.name,
|
||||
{
|
||||
"value": attribute.value ?? "",
|
||||
errors,
|
||||
"doDisplayPotentialErrorMessages": errors.length !== 0
|
||||
}
|
||||
])
|
||||
),
|
||||
[attributesWithPassword]
|
||||
);
|
||||
type FormFieldState_internal = Omit<FormFieldState, "displayableError"> & {
|
||||
errors: FormFieldError[];
|
||||
hasLostFocusAtLeastOnce: boolean;
|
||||
};
|
||||
|
||||
type InternalState = typeof initialInternalState;
|
||||
type State = FormFieldState_internal[];
|
||||
|
||||
const [formValidationInternalState, formValidationDispatch] = useReducer(
|
||||
(
|
||||
state: InternalState,
|
||||
params:
|
||||
| {
|
||||
action: "update value";
|
||||
name: string;
|
||||
newValue: string;
|
||||
}
|
||||
| {
|
||||
action: "focus lost";
|
||||
name: string;
|
||||
}
|
||||
): InternalState => ({
|
||||
...state,
|
||||
[params.name]: {
|
||||
...state[params.name],
|
||||
...(() => {
|
||||
switch (params.action) {
|
||||
case "focus lost":
|
||||
return { "doDisplayPotentialErrorMessages": true };
|
||||
case "update value":
|
||||
return {
|
||||
"value": params.newValue,
|
||||
const [state, dispatchFormAction] = useReducer(
|
||||
(state: State, params: FormAction): State => {
|
||||
if (params.action === "add value to multi-valued attribute") {
|
||||
const formFieldStates = state.filter(({ name }) => name === params.name);
|
||||
|
||||
state.splice(state.indexOf(formFieldStates[formFieldStates.length - 1]) + 1, 0, {
|
||||
"index": formFieldStates.length,
|
||||
"name": params.name,
|
||||
"value": "",
|
||||
"errors": getErrors({
|
||||
"name": params.name,
|
||||
"fieldValueByAttributeName": {
|
||||
...state,
|
||||
[params.name]: { "value": params.newValue }
|
||||
}
|
||||
})
|
||||
};
|
||||
}
|
||||
})()
|
||||
}
|
||||
"index": formFieldStates.length,
|
||||
"fieldValues": state
|
||||
}),
|
||||
initialInternalState
|
||||
"hasLostFocusAtLeastOnce": false
|
||||
});
|
||||
|
||||
return state;
|
||||
}
|
||||
|
||||
const formFieldState = state.find(({ name, index }) => name === params.name && index === params.index);
|
||||
|
||||
assert(formFieldState !== undefined);
|
||||
|
||||
switch (params.action) {
|
||||
case "focus lost":
|
||||
formFieldState.hasLostFocusAtLeastOnce = true;
|
||||
return state;
|
||||
case "update value":
|
||||
formFieldState.value = params.newValue;
|
||||
formFieldState.errors = getErrors({
|
||||
"name": params.name,
|
||||
"index": params.index,
|
||||
"fieldValues": state
|
||||
});
|
||||
return state;
|
||||
}
|
||||
|
||||
assert<Equals<typeof params, never>>(false);
|
||||
},
|
||||
useMemo(function getInitialState(): State {
|
||||
const initialFormFieldValues = (() => {
|
||||
const initialFormFieldValues: Param0<typeof getErrors>["fieldValues"] = [];
|
||||
|
||||
for (const attribute of attributesWithPassword) {
|
||||
handle_multi_valued_attribute: {
|
||||
if (!attribute.multivalued) {
|
||||
break handle_multi_valued_attribute;
|
||||
}
|
||||
|
||||
const values = attribute.values ?? [attribute.value ?? ""];
|
||||
|
||||
for (let index = 0; index < values.length; index++) {
|
||||
initialFormFieldValues.push({
|
||||
"name": attribute.name,
|
||||
index,
|
||||
"value": values[index]
|
||||
});
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
initialFormFieldValues.push({
|
||||
"name": attribute.name,
|
||||
"index": 0,
|
||||
"value": attribute.value ?? ""
|
||||
});
|
||||
}
|
||||
|
||||
return initialFormFieldValues;
|
||||
})();
|
||||
|
||||
const initialState: State = initialFormFieldValues.map(({ name, index, value }) => ({
|
||||
name,
|
||||
index,
|
||||
value,
|
||||
"errors": getErrors({
|
||||
"name": name,
|
||||
index,
|
||||
"fieldValues": initialFormFieldValues
|
||||
}),
|
||||
"hasLostFocusAtLeastOnce": false
|
||||
}));
|
||||
|
||||
return initialState;
|
||||
}, [])
|
||||
);
|
||||
|
||||
const formValidationState = useMemo(
|
||||
const formState: FormState = useMemo(
|
||||
() => ({
|
||||
"fieldStateByAttributeName": Object.fromEntries(
|
||||
Object.entries(formValidationInternalState).map(([name, { value, errors, doDisplayPotentialErrorMessages }]) => [
|
||||
"formFieldStates": state.map(({ name, index, value, errors, hasLostFocusAtLeastOnce }) => ({
|
||||
name,
|
||||
{ value, "displayableErrors": doDisplayPotentialErrorMessages ? errors : [] }
|
||||
])
|
||||
),
|
||||
"isFormSubmittable": Object.entries(formValidationInternalState).every(
|
||||
([name, { value, errors }]) =>
|
||||
errors.length === 0 && (value !== "" || !attributesWithPassword.find(attribute => attribute.name === name)!.required)
|
||||
)
|
||||
index,
|
||||
value,
|
||||
"displayableError": hasLostFocusAtLeastOnce ? errors : []
|
||||
})),
|
||||
"isFormSubmittable": state.every(({ errors }) => errors.length === 0)
|
||||
}),
|
||||
[formValidationInternalState, attributesWithPassword]
|
||||
[state]
|
||||
);
|
||||
|
||||
return {
|
||||
formValidationState,
|
||||
formValidationDispatch,
|
||||
formState,
|
||||
dispatchFormAction,
|
||||
attributesWithPassword
|
||||
};
|
||||
}
|
||||
@ -183,31 +252,43 @@ export function useFormValidation(params: {
|
||||
function useGetErrors(params: {
|
||||
kcContext: {
|
||||
messagesPerField: Pick<KcContext.Common["messagesPerField"], "existsError" | "get">;
|
||||
profile: {
|
||||
attributes: { name: string; value?: string; validators: Validators }[];
|
||||
};
|
||||
};
|
||||
attributes: {
|
||||
name: string;
|
||||
validators: Validators;
|
||||
value?: string;
|
||||
values?: string[];
|
||||
required?: boolean;
|
||||
}[];
|
||||
i18n: I18n;
|
||||
}) {
|
||||
const { kcContext, i18n } = params;
|
||||
const { kcContext, attributes, i18n } = params;
|
||||
|
||||
const {
|
||||
messagesPerField,
|
||||
profile: { attributes }
|
||||
} = kcContext;
|
||||
const { messagesPerField } = kcContext;
|
||||
|
||||
const { msg, msgStr, advancedMsg, advancedMsgStr } = i18n;
|
||||
|
||||
const getErrors = useConstCallback((params: { name: string; fieldValueByAttributeName: Record<string, { value: string }> }) => {
|
||||
const { name, fieldValueByAttributeName } = params;
|
||||
const getErrors = useConstCallback(
|
||||
(params: { name: string; index: number; fieldValues: { name: string; index: number; value: string }[] }): FormFieldError[] => {
|
||||
const { name, index, fieldValues } = params;
|
||||
|
||||
const { value } = fieldValueByAttributeName[name];
|
||||
const value = (() => {
|
||||
const fieldValue = fieldValues.find(fieldValue => fieldValue.name === name && fieldValue.index === index);
|
||||
|
||||
const { value: defaultValue, validators } = attributes.find(attribute => attribute.name === name)!;
|
||||
assert(fieldValue !== undefined);
|
||||
|
||||
block: {
|
||||
if ((defaultValue ?? "") !== value) {
|
||||
break block;
|
||||
return fieldValue.value;
|
||||
})();
|
||||
|
||||
const attribute = attributes.find(attribute => attribute.name === name);
|
||||
|
||||
assert(attribute !== undefined);
|
||||
|
||||
server_side_error: {
|
||||
const defaultValue = (attribute.values !== undefined ? attribute.values[index] : attribute.value) ?? "";
|
||||
|
||||
if (defaultValue !== value) {
|
||||
break server_side_error;
|
||||
}
|
||||
|
||||
let doesErrorExist: boolean;
|
||||
@ -215,11 +296,11 @@ function useGetErrors(params: {
|
||||
try {
|
||||
doesErrorExist = messagesPerField.existsError(name);
|
||||
} catch {
|
||||
break block;
|
||||
break server_side_error;
|
||||
}
|
||||
|
||||
if (!doesErrorExist) {
|
||||
break block;
|
||||
break server_side_error;
|
||||
}
|
||||
|
||||
const errorMessageStr = messagesPerField.get(name);
|
||||
@ -233,25 +314,41 @@ function useGetErrors(params: {
|
||||
];
|
||||
}
|
||||
|
||||
const errors: {
|
||||
errorMessage: JSX.Element;
|
||||
errorMessageStr: string;
|
||||
validatorName: keyof Validators | undefined;
|
||||
}[] = [];
|
||||
const errors: FormFieldError[] = [];
|
||||
|
||||
scope: {
|
||||
const { validators } = attribute;
|
||||
|
||||
required_field: {
|
||||
if (!attribute.required) {
|
||||
break required_field;
|
||||
}
|
||||
|
||||
if (value !== "") {
|
||||
break required_field;
|
||||
}
|
||||
|
||||
const msgArgs = ["error-user-attribute-required"] as const;
|
||||
|
||||
errors.push({
|
||||
"validatorName": undefined,
|
||||
"errorMessage": <Fragment key={errors.length}>{msg(...msgArgs)}</Fragment>,
|
||||
"errorMessageStr": msgStr(...msgArgs)
|
||||
});
|
||||
}
|
||||
|
||||
validator_x: {
|
||||
const validatorName = "length";
|
||||
|
||||
const validator = validators[validatorName];
|
||||
|
||||
if (validator === undefined) {
|
||||
break scope;
|
||||
break validator_x;
|
||||
}
|
||||
|
||||
const { "ignore.empty.value": ignoreEmptyValue = false, max, min } = validator;
|
||||
|
||||
if (ignoreEmptyValue && value === "") {
|
||||
break scope;
|
||||
break validator_x;
|
||||
}
|
||||
|
||||
if (max !== undefined && value.length > parseInt(max)) {
|
||||
@ -275,34 +372,36 @@ function useGetErrors(params: {
|
||||
}
|
||||
}
|
||||
|
||||
scope: {
|
||||
validator_x: {
|
||||
const validatorName = "_compareToOther";
|
||||
|
||||
const validator = validators[validatorName];
|
||||
|
||||
if (validator === undefined) {
|
||||
break scope;
|
||||
break validator_x;
|
||||
}
|
||||
|
||||
const { "ignore.empty.value": ignoreEmptyValue = false, name: otherName, shouldBe, "error-message": errorMessageKey } = validator;
|
||||
|
||||
if (ignoreEmptyValue && value === "") {
|
||||
break scope;
|
||||
break validator_x;
|
||||
}
|
||||
|
||||
const { value: otherValue } = fieldValueByAttributeName[otherName];
|
||||
const otherFieldValue = fieldValues.find(fieldValue => fieldValue.name === otherName);
|
||||
|
||||
assert(otherFieldValue !== undefined);
|
||||
|
||||
const isValid = (() => {
|
||||
switch (shouldBe) {
|
||||
case "different":
|
||||
return otherValue !== value;
|
||||
return otherFieldValue.value !== value;
|
||||
case "equal":
|
||||
return otherValue === value;
|
||||
return otherFieldValue.value === value;
|
||||
}
|
||||
})();
|
||||
|
||||
if (isValid) {
|
||||
break scope;
|
||||
break validator_x;
|
||||
}
|
||||
|
||||
const msgArg = [
|
||||
@ -329,23 +428,23 @@ function useGetErrors(params: {
|
||||
});
|
||||
}
|
||||
|
||||
scope: {
|
||||
validator_x: {
|
||||
const validatorName = "pattern";
|
||||
|
||||
const validator = validators[validatorName];
|
||||
|
||||
if (validator === undefined) {
|
||||
break scope;
|
||||
break validator_x;
|
||||
}
|
||||
|
||||
const { "ignore.empty.value": ignoreEmptyValue = false, pattern, "error-message": errorMessageKey } = validator;
|
||||
|
||||
if (ignoreEmptyValue && value === "") {
|
||||
break scope;
|
||||
break validator_x;
|
||||
}
|
||||
|
||||
if (new RegExp(pattern).test(value)) {
|
||||
break scope;
|
||||
break validator_x;
|
||||
}
|
||||
|
||||
const msgArgs = [errorMessageKey ?? id<MessageKey>("shouldMatchPattern"), pattern] as const;
|
||||
@ -357,9 +456,9 @@ function useGetErrors(params: {
|
||||
});
|
||||
}
|
||||
|
||||
scope: {
|
||||
validator_x: {
|
||||
if ([...errors].reverse()[0]?.validatorName === "pattern") {
|
||||
break scope;
|
||||
break validator_x;
|
||||
}
|
||||
|
||||
const validatorName = "email";
|
||||
@ -367,17 +466,17 @@ function useGetErrors(params: {
|
||||
const validator = validators[validatorName];
|
||||
|
||||
if (validator === undefined) {
|
||||
break scope;
|
||||
break validator_x;
|
||||
}
|
||||
|
||||
const { "ignore.empty.value": ignoreEmptyValue = false } = validator;
|
||||
|
||||
if (ignoreEmptyValue && value === "") {
|
||||
break scope;
|
||||
break validator_x;
|
||||
}
|
||||
|
||||
if (emailRegexp.test(value)) {
|
||||
break scope;
|
||||
break validator_x;
|
||||
}
|
||||
|
||||
const msgArgs = [id<MessageKey>("invalidEmailMessage")] as const;
|
||||
@ -389,19 +488,19 @@ function useGetErrors(params: {
|
||||
});
|
||||
}
|
||||
|
||||
scope: {
|
||||
validator_x: {
|
||||
const validatorName = "integer";
|
||||
|
||||
const validator = validators[validatorName];
|
||||
|
||||
if (validator === undefined) {
|
||||
break scope;
|
||||
break validator_x;
|
||||
}
|
||||
|
||||
const { "ignore.empty.value": ignoreEmptyValue = false, max, min } = validator;
|
||||
|
||||
if (ignoreEmptyValue && value === "") {
|
||||
break scope;
|
||||
break validator_x;
|
||||
}
|
||||
|
||||
const intValue = parseInt(value);
|
||||
@ -415,7 +514,7 @@ function useGetErrors(params: {
|
||||
"errorMessageStr": msgStr(...msgArgs)
|
||||
});
|
||||
|
||||
break scope;
|
||||
break validator_x;
|
||||
}
|
||||
|
||||
if (max !== undefined && intValue > parseInt(max)) {
|
||||
@ -427,7 +526,7 @@ function useGetErrors(params: {
|
||||
"errorMessageStr": msgStr(...msgArgs)
|
||||
});
|
||||
|
||||
break scope;
|
||||
break validator_x;
|
||||
}
|
||||
|
||||
if (min !== undefined && intValue < parseInt(min)) {
|
||||
@ -439,25 +538,25 @@ function useGetErrors(params: {
|
||||
"errorMessageStr": msgStr(...msgArgs)
|
||||
});
|
||||
|
||||
break scope;
|
||||
break validator_x;
|
||||
}
|
||||
}
|
||||
|
||||
scope: {
|
||||
validator_x: {
|
||||
const validatorName = "options";
|
||||
|
||||
const validator = validators[validatorName];
|
||||
|
||||
if (validator === undefined) {
|
||||
break scope;
|
||||
break validator_x;
|
||||
}
|
||||
|
||||
if (value === "") {
|
||||
break scope;
|
||||
break validator_x;
|
||||
}
|
||||
|
||||
if (validator.options.indexOf(value) >= 0) {
|
||||
break scope;
|
||||
break validator_x;
|
||||
}
|
||||
|
||||
const msgArgs = [id<MessageKey>("notAValidOption")] as const;
|
||||
@ -472,7 +571,8 @@ function useGetErrors(params: {
|
||||
//TODO: Implement missing validators.
|
||||
|
||||
return errors;
|
||||
});
|
||||
}
|
||||
);
|
||||
|
||||
return { getErrors };
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user