簡體   English   中英

我如何訪問路徑並查看使用 JOI 驗證返回的錯誤消息

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

我正在嘗試使用 joi 驗證方法,但我無法訪問從 object 返回的路徑或消息正確地安慰

    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");
    }
}

希望你現在已經明白了 但是,以防萬一,如果你使用的是最新版本的 Joi,那么如果你查看文檔,你會發現現在正在對模式調用驗證方法,而不是 Joi object本身,這意味着您可以像 Schema 一樣進行操作。 validate() 而不是 Joi.validate()。 好吧,快樂的編碼:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM