Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

reactjs - Yup: How to validate field only when it exists?

Is it possible to validate a field only when it exists?

I'm going to create an application. A field(email) may / may not display on step 2, it depends on the step 1's selected option. The problem is that I can't put email: Yup.string().Required(), it causes that the validation run all the time even the field is not displayed.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can set a additional boolean key where value is default false. Change it to true when you modify the value in step 1. And then if the value is true for that key then apply the validation.

Something like this.


    const initialSchema= {
      name: '',
      isEmail: false, // change this when you want to add validation
      email: '',
      phone: '',
    };
    
    const validationSchema = Yup.object().shape({
      name: Yup.string()
        .required('Enter Name')
      isEmail: Yup.boolean(),
      email: Yup.string().when('isEmail', {
         is: true,
         then: Yup.string()
         .required('Enter Email ID'),
         otherwise: Yup.string(),
      }),
      phone: Yup.string()
        .required('Enter Mobile No'),
    });

Here is the documentation reference for same.

Update:

Here is the working codesandbox. I've added checkbox with display:none;, and added the default state values in data context.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...