Skip to content

Instantly share code, notes, and snippets.

@epicbytes
Created September 20, 2022 20:29
Show Gist options
  • Save epicbytes/f13550e0c961c865098abf4d7786c8df to your computer and use it in GitHub Desktop.
Save epicbytes/f13550e0c961c865098abf4d7786c8df to your computer and use it in GitHub Desktop.
import { validate, define } from "superstruct";
export function validatePhoneForE164(phoneNumber: string) {
const regEx = /^\+[1-9]\d{10,14}$/;
return regEx.test("+" + phoneNumber.replace(/\D/g, ""));
}
export const isAccept = define("isAccept", (value, context) => !!value);
export function CustomValidator<T>(
{
values,
meta,
}: Pick<FormValidateParams<T, Record<string, unknown>>, "values" | "meta">,
scheme: Struct<T, any>,
messages: any
): ErrorsInline {
const [result] = validate(values, scheme);
return Object.fromEntries(
result
?.failures()
.map((validationResult) => [
validationResult.key,
messages[validationResult.key as keyof T]?.[
`${validationResult.type}${
validationResult.refinement ? "_" + validationResult.refinement : ""
}`
] || validationResult.message,
]) || []
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment