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.

exportfunctionuseValidator(rules,inputs){const[isSubmited,setIsSubmited]=useState(false);constvalidatorLib=require("validator");constforceValid=()=>{constvalidation={isInvalid: false,};rules.forEach((rule)=>{validation[rule.field]={isInvalid: false};});returnvalidation;};constvalidate=()=>{// start out assuming valid.constvalidation=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.constvalue=`${inputs[rule.field]??""}`;constargs=rule.args??[];constmethod=typeofrule.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,};}}});returnvalidation;};constvalidation=validate();constisInvalid=validation.isInvalid;constvalidator=isSubmited ? validation : forceValid();return{ isSubmited, setIsSubmited, isInvalid, validator };}

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