react-final-form icon indicating copy to clipboard operation
react-final-form copied to clipboard

Why is Validation not working with Joi?

Open Gr8z opened this issue 7 years ago • 4 comments

Hi, I have a simple review form using Joi validator.

The error fields never appear. Even though I can see them in the console.log

Here is my code:

schemas.js

import Joi from "@hapi/joi";

// Review Form
export const reviewSchema = Joi.object().keys({
  rating: Joi.number().required(),
  text: Joi.string()
    .min(3)
    .max(600)
    .required()
});

// Validator for final form
export const validator = (values, schema) => {
  Joi.validate(values, schema, { abortEarly: false }, (err, val) => {
    if (err) {
      const errors = err.details.reduce(
        (errors, error) => ({
          ...errors,
          [error.path]: error.message
        }),
        {}
      );

      console.log("err.details: ", errors); // {rating: ""rating" is required", text: ""text" is required"}
      return errors;
    }
    return {};
  });
};

AddonAddReview.js

import React, { Component } from "react";
import { connect } from "react-redux";
import { Form, Field } from "react-final-form";

import { reviewSchema, validator } from "../../../utils/schemas";
import { postAddonReview } from "../../../actions/addonsActions";

class AddonAddReview extends Component {
  render() {
    const { handle } = this.props.addon;
    return (
      <Form
        validate={values => {
          return validator(values, reviewSchema);
        }}
        onSubmit={values =>
          this.props.postAddonReview(handle, values, this.closeButton)
        }
        validateOnBlur
        render={({ handleSubmit, submitting, pristine }) => (
          <form className="nobottommargin" onSubmit={handleSubmit}>
            <div className="col_full col_last">
              <Field
                id="reviewform-rating"
                name="rating"
                label="Rating"
                component={SelectInputField}
              >
                <option value="">-- Select One --</option>
                <option value="1">1</option>
                <option value="2">2</option>
                <option value="3">3</option>
                <option value="4">4</option>
                <option value="5">5</option>
              </Field>
            </div>
            <div className="clear" />
            <div className="col_full">
              <Field
                id="reviewform-comment"
                label="Comment"
                name="text"
                rows="6"
                cols="30"
                component={TextAreaInputField}
                type="text"
              />
              <Field name="rating">
                {fieldState => (
                  <pre>{JSON.stringify(fieldState, undefined, 2)}</pre>
                )}
              </Field>
            </div>
            <div className="col_full nobottommargin">
              <button
                className="button button-3d nomargin"
                type="submit"
                id="reviewform-submit"
                name="reviewform-submit"
                disabled={submitting || pristine}
              >
                {submitting ? (
                  <span className="spinner-border spinner-border-sm" />
                ) : (
                  "Submit Review"
                )}
              </button>
            </div>
          </form>
        )}
      />
    );
  }
}

const TextAreaInputField = ({ input, meta, ...rest }) => (
  <div>
    <label htmlFor={rest.id}>
      {rest.label}
      {rest.required && <small>*</small>}
    </label>
    <textarea {...input} {...rest} />
    {meta.touched && meta.error && (
      <div className="invalid-feedback">{meta.error}</div>
    )}
  </div>
);

const SelectInputField = ({ input, meta, ...rest }) => (
  <div>
    <label htmlFor={rest.id}>
      {rest.label}
      {rest.required && <small>*</small>}
    </label>
    <select {...input} {...rest} />
    {meta.touched && meta.error && (
      <div className="invalid-feedback">{meta.error}</div>
    )}
  </div>
);

const mapStateToProps = state => ({
  addon: state.addon.current
});

export default connect(
  mapStateToProps,
  { postAddonReview }
)(AddonAddReview);

Any clues?

Gr8z avatar Jul 06 '19 13:07 Gr8z

Solved it. My idiot self left the return inside the Joi callback.

schemas.js (fixed)

import Joi from "@hapi/joi";

// Review Form
export const reviewSchema = Joi.object().keys({
 rating: Joi.number().required(),
 text: Joi.string()
   .min(3)
   .max(600)
   .required()
});

// Validator for final form
export const validator = (values, schema) => {
 let errors = {};
 Joi.validate(values, schema, { abortEarly: false }, (err, val) => {
   if (err) {
     errors = err.details.reduce(
       (errors, error) => ({
         ...errors,
         [error.path]: error.message
       }),
       {}
     );
   }
 });
 return errors;
};

Here is the fixed file if someone encountered something similar. Just move return errors; outside the promise.

Also btw, if anyone is wondering how to implement Joi validation with Final form. This is the way.

Gr8z avatar Jul 06 '19 13:07 Gr8z

If you could show the "before" and "after", it might help a future person finding this ticket.

We've all wasted days on stupid stuff like that. You're not alone. 😄

erikras avatar Jul 06 '19 14:07 erikras

Done @erikras

Thank you so much for this awesome package.

Gr8z avatar Jul 06 '19 14:07 Gr8z

function validateProfile(user){
    const schema=Joi.object({
        skills:Joi.string().required(),
        status:Joi.string().required(),
       
    })
    return schema.validate(user);
}

This is my code for validating profile but I am getting an error image

shahjigar556 avatar Feb 10 '21 19:02 shahjigar556