Formik validate react Rating component

Viewed 908

I need to validate react Rating component by Formik to make it required, by default no stars selected. So I have code in my component:

validateRating(value) {

    let error;
    if (!value || value === 0) {
        error = 'Required';
    }
    return error;
}  

render() {

    const ModelSchema = Yup.object().shape({
        rating: Yup.number()
            .required('Please rate this product.'),
       });

    return (
        <div>
            <Formik ...


<Field name="rating" id="rating" type="number" validate={this.validateRating}>
    {({ field: { value }, form: { setFieldValue } }) => (
    <div>
        <Rating
            placeholderRating={3}
            emptySymbol={<FontAwesomeIcon icon={farStar} size="lg" style={{color:"#aaa"}} />}
            fullSymbol={<FontAwesomeIcon icon={fasStar} size="lg" style={{color:"#ffd200"}} />}
            placeholderSymbol={<FontAwesomeIcon icon={fasStar} size="lg" style={{color:"#aaa"}} />}
            onChange={this.ratingChange} initialRating={this.state.Rating}
        />                                                                        

    </div>
    )}
</Field>
<ErrorMessage name="rating" component="small" className="form-text text-danger" />

It goes into validateRating function, but with undefined value. Appreciate any help what I'm doing wrong. Thank you!

1 Answers

What I needed is to set initial value in initialValues

<Formik
    initialValues={{
        rating: 0
    }}

and it works. Hope it could help someone. Thank you.

Related