Skip to content

Re-implementation to use react hooks. #5

Description

@pedegago

It is incredible! at the day of today I keep using this implementation in all my projects but today I wrote it as a react hook and I want to share with the comunity my solution. This solution will be improved by me soon.

export function useValidator(rules, inputs) {
    const [isSubmited, setIsSubmited] = useState(false);
    const validatorLib = require("validator");

    const forceValid = () => {
        const validation = {
            isInvalid: false,
        };

        rules.forEach((rule) => {
            validation[rule.field] = { isInvalid: false };
        });

        return validation;
    };

    const validate = () => {
        // start out assuming valid.
        const validation = forceValid();

        rules.forEach((rule) => {
            // if the field hasn't already been marked
            // invalid by an earlier rule.
            if (!validation[rule.field].isInvalid) {
                // determine the field value, the method to invoke
                // and optional args from the rule definition.
                const value = `${inputs[rule.field] ?? ""}`;
                const args = rule.args ?? [];
                const method =
                    typeof rule.method === "string"
                        ? validatorLib[rule.method]
                        : rule.method;

                // Call the validation method with the current field value as the first
                // argument, any additional arguments, and the whole state as a final
                // argument. If the result doesn't match the rule.validWhen property,
                // then set the isInvalid field to false and modify the validation
                // object for the field.
                if (method(value, ...args, { ...inputs }) !== rule.validWhen) {
                    validation.isInvalid = true;
                    validation[rule.field] = {
                        isInvalid: true,
                        message: rule.message,
                    };
                }
            }
        });

        return validation;
    };

    const validation = validate();
    const isInvalid = validation.isInvalid;
    const validator = isSubmited ? validation : forceValid();

    return { isSubmited, setIsSubmited, isInvalid, validator };
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions