简体   繁体   中英

how can i access the path and see the message of an error returned using JOI validation

i'm trying to use joi validation method and i can't access the path or message returned from the object i tried to follow some videos to know more yet no effects the whole problem is that i can't access the joi object though it's consoled correctly

    state ={
    username : "",
    password : "",
    errors :{}
};


schema =Joi.object().keys({
    username: Joi.string().required(),
    password:Joi.string().required()
})

validate = ()=>{
    const errors = {};
            const res = Joi.validate(this.state,this.schema,{abortEarly:false});
    console.log(res);        
    if (res.error===null ){
        this.setState({errors:{}});
        return null;
    }
    // this is where i get the error and can't access it 
    for (const error of res.error.details){
        errors[error.path] = error.message;
    }
    this.setState({errors});

}
handleSubmit=(e)=>{
    e.preventDefault();
    const errors = this.validate();
    if(errors){return}
    else{
        //call backend
        console.log("Passed");
    }
}

Hopefully you have already figured it out now However, just in case, if you are using the lastest version of Joi, then if you look at the document, you will find the validate method now is being called on the schema, not the Joi object itself, which means you can do it like Schema. validate() instead of Joi.validate(). Alright, happy coding:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM