jquense / yup

Dead simple Object schema validation
MIT License
22.89k stars 933 forks source link

Validate single field at a time #615

Closed reharik closed 5 years ago

reharik commented 5 years ago

Hi, I'm trying to use Yup with Formik for validation. Formik has Yup specific integration for validating a whole form before submission. However, most form use cases will validate the specific input you are on when you step out ( blur ). Formik has this feature but I can't see anyway to do it with the schema I have already defined with Yup. I would have to write a function for each input to check for the exact same things I just defined in the Yup schema. So a) am I missing something in Yup? and b) if not can we please have that feature. Thanks

reharik commented 5 years ago

So I was able to address this problem by adding the following code to where I define the yupSchema

yupSchema.validateSingleField = (fieldName, value) => { const fieldSchema = yup.object().shape({[fieldName]: yupSchema.fields[fieldName]}); if(!fieldSchema.isValidSync()) { return fieldSchema.validateSync({ [fieldName]: value }); } };

Then it's used like

const validate = val => schema.validateSingleField(field.field_name, field.title, val); return ( <Field ...blah validate={validate} /> )

Not sure why it's not formatting for me. Sorry. It would be nice if a) yup provided us with this, and b) yup provided for a "friendlyName" property on the schema so that the error messages was "Customer First Name is required" rather than "cust_f_name". I know that's partially our fault for having stupid names for our properties, don't get me started, but concern still stands even if prop name is "customerFirstName"

So I'm not closing this because I'd like to hear a) if I"m missing an easier implementation and b) if not the would Yup consider implementing something like this.

Thanks

jquense commented 5 years ago

you can use validateAt to validate a single field

vainik17 commented 5 years ago

i have a four text field with yup validation. first i enter value in last field so it's showing all field "required" error. i want to only last field onChange instead of all field. how can i do it and how to work validateAt . I use validationSchema in withFormik

jquense commented 5 years ago

That is a Formik support question not a yup one, I'd suggest asking over there

vainik17 commented 5 years ago

@jquense thanks for your response I solved this problem It's formik side problem

redfoggg commented 3 years ago

So you solved this problem and don't give a link, this is a really evil deed...