skip to Main Content

a have object like this

const foo = {
 person: {
 name:"Jon",
 sex:"men"
}, 
 job: "drinker"
};

When i use console.log(foo.person.name) l got undefined. And can’t validate my object

Question: how i can validate foo.person.name.

2

Answers


  1. You can use optional chaining and pre check if the value exists or not.

    const foo = {
      person: {
        name: "Jon",
        sex: "men"
      },
      job: "drinker"
    };
    const name = foo?.person?.name ?? "Name is not available";
    
    Login or Signup to reply.
  2. Yup is a schema builder for runtime value parsing and validation.
    So defining the correct datatype is very crucial. In your case you are trying to define a object, so you can try something like:

      const obj = object({
      person: object({
            name: string().min(3).lowercase().trim() 
            sex: string().max(4).lowercase().trim()
            }),
          job: string().max(10) //add what validations you need
      })
      .json()
    

    If you need further help with this you can go through Yup Readme on npm

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search