Sprint 2 and Validation

The last two weeks have been pretty hectic for me. My wife and I are moving soon and we recently put an offer in on a house and it was accepted! Other than that news for me I have been working on the capstone project in the short amount of time in between looking for a house, work, and my other class.

For the 2 week sprint, my goal was to create some reusable React components for text input, a list of experiences, and dropdowns, and also create the create a trip form page. I started off by working on the text input with some of the basic things that a text input needs. For example a label, value, type, and hint. Which was pretty simple since we are also using React-Bootstrap for our project. This library is actually one of the oldest React libraries.

Once I had finished with the reusable components it was time to start on our first form. The trip form is, at the moment, just a name, but later on, we will be adding functionality for a description to add as well, and maybe a start and end date. There is one thing that I did not take into account and that was form validation. Luckily my fellow teammate had a pretty simple solution. Instead of creating our own form validation by hand. He decided to look into Fromik and Yup.

Formik is designed to manage forms with complex validation. This coupled with Yup which is a validation schema package that is actually very similar to express-validator or Joi if any backend express developers have ever used those. You basically tell it what value you want to validate and give it some constraints and a message that will show if the validation fails.

const validationSchema = Yup.object().shape({
	username: Yup.string()
                .min(2, 'Minumum 2 characters')
                .max(30, 'Maximum 30 characters')
                .required("Required"),
	password: Yup.string()
                .required('No password provided.') 
                .min(8, 'Minimum 8 characters')
                .matches(/[a-zA-Z]/, 'Password can letters.')
                .required("Required"),
});

Once you have your validation schema ready you can pass it as a prop in the Formik component, and also pass some initial values that will be for your form. You can also need to pass some functions that come with Formik that will handle common functions for forms including handleChange and handleSubmit.

<Formik
    initialValues={{
    username: "",
    password: "",
    }}
    validationSchema={validationSchema}
    {({
        handleSubmit,
        handleChange,
        isSubmitting,
        values,
    }) => (Form Goes Here)
></Formik>

After that, you are pretty much set up to handle some form validation in your new React application!

Print Friendly, PDF & Email

Leave a Reply

Your email address will not be published. Required fields are marked *