How to do login form validation in Reactjs

How to do login form validation in Reactjs

This is a step-by-step tutorial that will show you how to do basic login form. Want to learn how to do login form validation in Reactjs?

For almost every login form that you create, you will want some sort of validation. In Reactjs, working with and validating forms can be a bit verbose, so in this article we are going to use a package called Formik to help us out!

Table of Contents

  • Creating the Reactjs Project
  • Installing Necessary Packages
  • Creating the Validated Form Component
  • Display the Login Form
  • Adding Validation Messages Logic
  • Displaying Validation/Error Messages
  • Test it Out
  • Conclusion


TLDR

  • Create a Reactjs project
  • Add the Formik (and Yup) packages
  • Customize the Formik component with an onSubmit callback and a validate function for error messages
  • then display those error messages to the user.> View the final code on CodeSandbox!

Here's a sneak peak at what we are going to create.


Creating the Reactjs Project

For this demo, I'll be using CodeSandbox. You can use CodeSandbox as well or use your local environment. Totally up to you.

Regardless of what you use for this demo, you need to start with a new React app using Create React App. In CodeSandbox, I'm going to choose to do just that.


Installing Necessary Packages

Now that we have our initial project created, we need to install three packages.

  • Formik - makes handling validation, error messages, and form submission easier
  • Email-validator - tiny package to validate emails (I hope this one is self-explanatory : )
  • Yup - schema validator that is commonly used in conjuntion with Formik

Formik

In your terminal, you'll need to install Formik.

npm install Formik

I'll do the same in the CodeSandbox dependency GUI.


Email-Validator

Now install email-validator.

npm install email-validator

Again installing from the CodeSandbox GUI.


Yup


npm install Yup


And again in CodeSandbox.


Creating the Validated Form Component

Now, we can start to stub out our ValidatedFormComponent. For now, we just want to create the basics and import it into the root file in the app to see it get displayed.

  • Create new functional component
  • Add dummy display content
  • Import in index.js

So, create a new file in your src **directory called ValidatedLoginForm.js. **Inside of that file, add the basic code for a functional component.

import React from "react";
const ValidatedLoginForm = () => (
  <div>
    <h1>Validated Form Component</h1>
  </div>
);

export default ValidatedLoginForm;

Then, include it in your index.js file.

function App() {
return (
<div className="App">
<ValidatedLoginForm />
</div>
);
}

and you should see it displayed.

Now, let's start with the Formik stuff. First, import Formik, Email-Valiator, and Yup in your new component.

import { Formik } from "formik";
import _ as EmailValidator from "email-validator";
import _ as Yup from "yup";

Now, let's stub out the Formik tag with initial values. Think of initial values as setting your state initially.

You'll also need an onSubmit callback. This callback will take two parameters, *values and an object that we can destructure. The values represented the input values from your form. I'm adding some dummy code here to simulate an async login call, then logging out what the values are.

In the callback, I'm also calling the setSubmitting function that was destructured from the second parameters. This will allow us to enable/disable the submit button while the asynchronous login call is happening.

<Formik
initialValues={{ email: "", password: "" }}
onSubmit={(values, { setSubmitting }) => {
setTimeout(() => {
console.log("Logging in", values);
setSubmitting(false);
}, 500);
}}
>
<h1>Validated Login Form</h1>
</Formik>

Render Props

The Formik component uses render props to supply certain variables and functions to the form that we create. If you're not very familiar with render props, I would take a second to check out Render Props Explained.

In short, render props are used to pass properties to children elements of a component. In this case, Formik will pass properties to our form code, which is the child. Notice that I'm using destructuring to get a reference to several specific variables and functions.

    { props => {
const {
values,
touched,
errors,
isSubmitting,
handleChange,
handleBlur,
handleSubmit
} = props;
return (
<div>
<h1>Validated Login Form</h1>
</div>
);
}}
Display the Login Form

Now, we can actually start to write the code to display the form. For what it's worth, in the finished CodeSandbox, I also created a LoginForm.js *component to show how basic login forms are handled from scratch. You can also use that as a reference for the form we are going to add now.

The form is pretty simple with two inputs (email and password), labels for each, and a submit button.

{ props => {
const {
values,
touched,
errors,
isSubmitting,
handleChange,
handleBlur,
handleSubmit
} = props;
return (
<form onSubmit={handleSubmit}>
<label htmlFor="email">Email</label>
<input name="email" type="text" placeholder="Enter your email" />

      &lt;label htmlFor="email"&gt;Password&lt;/label&gt;
      &lt;input
        name="password"
        type="password"
        placeholder="Enter your password"
      /&gt;
      &lt;button type="submit" &gt;
        Login
      &lt;/button&gt;
    &lt;/form&gt;
  );
}}

Notice that the *onSubmit *is calling the *handleSubmit *from the props.

I mentioned earleir that we could disable our submit button while the user is already attempting to login. We can add that small change now by using the *isSubmitting *property that we destructured from props above.

  <button type="submit" disabled={isSubmitting}>
Login
</button>

I would recommend adding the CSS from the finished CodeSandbox as well. Otherwise you won't get the full effect. You can copy the below css into your styles.css file.

.App {
font-family: sans-serif;
}

h1 {
text-align: center;
}

form {
max-width: 500px;
width: 100%;
margin: 0 auto;
}

label,
input {
display: block;
width: 100%;
}

label {
margin-bottom: 5px;
height: 22px;
}

input {
margin-bottom: 20px;
padding: 10px;
border-radius: 3px;
border: 1px solid #777;
}

input.error {
border-color: red;
}

.input-feedback {
color: rgb(235, 54, 54);
margin-top: -15px;
font-size: 14px;
margin-bottom: 20px;
}

button {
padding: 10px 15px;
background-color: rgb(70, 153, 179);
color: white;
border: 1px solid rgb(70, 153, 179);
background-color: 250ms;
}

button:hover {
cursor: pointer;
background-color: white;
color: rgb(70, 153, 179);
}

Adding Validation Messages Logic

Now we need to figure out how to validate our inputs. The first question is, what constraints do we want to have on our input. Let's start with email. Email input should...

  • Be required
  • Look like a real email

Password input should...

  • Be required
  • Be at least 8 characters long
  • contain at least one number

We'll cover two ways to create these messages, one using Yup and one doing it yourself. We recommend using Yup and you'll see why shortly.


Doing it Yourself

The first option is creating our validate function. The purpose of the function is to iterate through the values of our form, validate these values in whatever way we see fit, and return an errors *object that has key value pairs of value->message.

Inside of the Formik tag, you can add the following code. This will always add an "Invalid email" error for email. We will start with this and go from there.

    validate={values => {
let errors = {};
errors.email = "Invalid email";
return errors;
}}

Now, we can ensure that the user has input something for the email.

validate={values => {
let errors = {};
if (!values.email) {
errors.email = "Required";
}
return errors;
}}

Then, we can check that the email is actually a valid looking email by using the email-validator package. This will look almost the same as the equivalent check for email.

  validate={values => {
let errors = {};
if (!values.email) {
errors.email = "Required";
} else if (!EmailValidator.validate(values.email)) {
errors.email = "Invalid email address";
}
return errors;
}}

That takes care of email, so now for password. We can first check that the user input something.

validate={values => {
let errors = {};
if (!values.password) {
errors.password = "Required";
}
return errors;
}}

Now we need to check the length to be at least 8 characters.

validate={values => {
const passwordRegex = /(?=.[0-9])/;
if (!values.password) {
errors.password = "Required";
} else if (values.password.length < 8) {
errors.password = "Password must be 8 characters long.";
}

  return errors;
}}

And lastly, that the password contains at least one number. For this, we can use regex.

 validate={values => {
let errors = {};

  const passwordRegex = /(?=.*[0-9])/;
  if (!values.password) {
    errors.password = "Required";
  } else if (values.password.length &lt; 8) {
    errors.password = "Password must be 8 characters long.";
  } else if (!passwordRegex.test(values.password)) {
    errors.password = "Invalida password. Must contain one number";
  }

  return errors;
}}

Here's the whole thing.

  validate={values => {
let errors = {};
if (!values.email) {
errors.email = "Required";
} else if (!EmailValidator.validate(values.email)) {
errors.email = "Invalid email address";
}

  const passwordRegex = /(?=.*[0-9])/;
  if (!values.password) {
    errors.password = "Required";
  } else if (values.password.length &lt; 8) {
    errors.password = "Password must be 8 characters long.";
  } else if (!passwordRegex.test(values.password)) {
    errors.password = "Invalida password. Must contain one number";
  }

  return errors;
}}

Using Yup (Recommended)

Ok, you might have noticed that handling the validate logic on our own gets a bit verbose. We have to manually do all of the checks ourselves. It wasn't that bad I guess, but with the Yup package, it gets all the more easy!

Yup is the recommended way to handle validation messages.

Yup makes input validation a breeze!

When using Yup, we no longer will see the Validate *property, but insead use validationSchema. Let's start with email. Here is the equivalent validation using Yup.

validationSchema={Yup.object().shape({
email: Yup.string()
.email()
.required("Required")
})}

Much shorter right?! Now, for password.

validationSchema={Yup.object().shape({
email: Yup.string()
.email()
.required("Required"),
password: Yup.string()
.required("No password provided.")
.min(8, "Password is too short - should be 8 chars minimum.")
.matches(/(?=.[0-9])/, "Password must contain a number.")
})}

Pretty SWEET!


Displaying Validation/Error Messages

Now that we have the logic for creating error messages, we need to display them. We will need to update the inputs in our form a bit.

We need to update several properties for both email and password inputs.

  • value
  • onChange
  • onBlur
  • className

Email

Let's start by updating value, onChange, and onBlur. Each of these will use properties from the render props.

<input
name="email"
type="text"
placeholder="Enter your email"
value={values.email}
onChange={handleChange}
onBlur={handleBlur}
/>

Then we can add a conditional "error" class if there are any errors. We can check for errors by looking at the errors object (remeber how we calculated that object ourselves way back when).

We can also check the touched property, to see whether or not the user has interacted with the email input before showing an error message.

<input
name="email"
type="text"
placeholder="Enter your email"
value={values.email}
onChange={handleChange}
onBlur={handleBlur}
className={errors.email && touched.email && "error"}
/>

And lastly, if there are errors, we will display them to the user. All in all, email will look like this.

<label htmlFor="email">Email</label>
<input
name="email"
type="text"
placeholder="Enter your email"
value={values.email}
onChange={handleChange}
onBlur={handleBlur}
className={errors.email && touched.email && "error"}
/>
{errors.email && touched.email && (
<div className="input-feedback">{errors.email}</div>
)}

Password

Now we need to do the same with password. I won't walk through each step beause they are exactly the same as email. Here's the final code.

<label htmlFor="email">Password</label>
<input
name="password"
type="password"
placeholder="Enter your password"
value={values.password}
onChange={handleChange}
onBlur={handleBlur}
className={errors.password && touched.password && "error"}
/>
{errors.password && touched.password && (
<div className="input-feedback">{errors.password}</div>
)}
Test it Out

Let's try it out! You can start by clicking the button without entering anything. You should see validation messages.

Now, we can get more specific for testing messages. Refresh your page to do this.Click inside of the email input, but don't type anything.

Then, click away from the input. You should see the "Required" message pop up. Notice that this message doesn't pop up automatically when the page loads. We only want to display error messages after the user has interacted with the input.

Now, start to type. You should get a message about not being a valid email.

And lastly, type in a valid looking email, and your error message goes away.

Now, same for password. Click on the input, then away, and you'll get the required message.

Then, start typing and you'll see the length validation.

Then, type 8 or more characters that does not include a number, and you'll see the "must contain a number" message.

And lastly, add a number, and error messages go away.


Conclusion

Whew, that was a long one! Again, validation can be a tricky thing, but with the help of a few packages, it becomes a bit easier. At the end of the day though, I think we've got a pretty legit login form with Reactjs!

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Learn More

React - The Complete Guide (incl Hooks, React Router, Redux)

Modern React with Redux [2019 Update]

React Native - The Practical Guide

MERN Stack Front To Back: Full Stack React, Redux & Node.js

Full-Stack Web Apps with Meteor and React

React Hooks

Getting started with React Router

The complete guide Handling a Forms in React 🚀🚀🚀

Svelte vs React vs Angular vs Vue

Best 50 React Interview Questions and Answers in 2019

Originally published on https://scotch.io

JavaScript developers should you be using Web Workers?

JavaScript developers should you be using Web Workers?

Do you think JavaScript developers should be making more use of Web Workers to shift execution off of the main thread?

Originally published by David Gilbertson at https://medium.com

So, Web Workers. Those wonderful little critters that allow us to execute JavaScript off the main thread.

Also known as “no, you’re thinking of Service Workers”.

Photo by Caleb Jones on Unsplash

Before I get into the meat of the article, please sit for a lesson in how computers work:

Understood? Good.

For the red/green colourblind, let me explain. While a CPU is doing one thing, it can’t be doing another thing, which means you can’t sort a big array while a user scrolls the screen.

This is bad, if you have a big array and users with fingers.

Enter, Web Workers. These split open the atomic concept of a ‘CPU’ and allow us to think in terms of threads. We can use one thread to handle user-facing work like touch events and rendering the UI, and different threads to carry out all other work.

Check that out, the main thread is green the whole way through, ready to receive and respond to the gentle caress of a user.

You’re excited (I can tell), if we only have UI code on the main thread and all other code can go in a worker, things are going to be amazing (said the way Oprah would say it).

But cool your jets for just a moment, because websites are mostly about the UI — it’s why we have screens. And a lot of a user’s interactions with your site will be tapping on the screen, waiting for a response, reading, tapping, looking, reading, and so on.

So we can’t just say “here’s some JS that takes 20ms to run, chuck it on a thread”, we must think about where that execution time exists in the user’s world of tap, read, look, read, tap…

I like to boil this down to one specific question:

Is the user waiting anyway?

Imagine we have created some sort of git-repository-hosting website that shows all sorts of things about a repository. We have a cool feature called ‘issues’. A user can even click an ‘issues’ tab in our website to see a list of all issues relating to the repository. Groundbreaking!

When our users click this issues tab, the site is going to fetch the issue data, process it in some way — perhaps sort, or format dates, or work out which icon to show — then render the UI.

Inside the user’s computer, that’ll look exactly like this.

Look at that processing stage, locking up the main thread even though it has nothing to do with the UI! That’s terrible, in theory.

But think about what the human is actually doing at this point. They’re waiting for the common trio of network/process/render; just sittin’ around with less to do than the Bolivian Navy.

Because we care about our users, we show a loading indicator to let them know we’ve received their request and are working on it — putting the human in a ‘waiting’ state. Let’s add that to the diagram.

Now that we have a human in the picture, we can mix in a Web Worker and think about the impact it will have on their life:

Hmmm.

First thing to note is that we’re not doing anything in parallel. We need the data from the network before we process it, and we need to process the data before we can render the UI. The elapsed time doesn’t change.

(BTW, the time involved in moving data to a Web Worker and back is negligible: 1ms per 100 KB is a decent rule of thumb.)

So we can move work off the main thread and have a page that is responsive during that time, but to what end? If our user is sitting there looking at a spinner for 600ms, have we enriched their experience by having a responsive screen for the middle third?

No.

I’ve fudged these diagrams a little bit to make them the gorgeous specimens of graphic design that they are, but they’re not really to scale.

When responding to a user request, you’ll find that the network and DOM-manipulating part of any given task take much, much longer than the pure-JS data processing part.

I saw an article recently making the case that updating a Redux store was a good candidate for Web Workers because it’s not UI work (and non-UI work doesn’t belong on the main thread).

Chucking the data processing over to a worker thread sounds sensible, but the idea struck me as a little, umm, academic.

First, let’s split instances of ‘updating a store’ into two categories:

  1. Updating a store in response to a user interaction, then updating the UI in response to the data change
  2. Not that first one

If the first scenario, a user taps a button on the screen — perhaps to change the sort order of a list. The store updates, and this results in a re-rendering of the DOM (since that’s the point of a store).

Let me just delete one thing from the previous diagram:

In my experience, it is rare that the store-updating step goes beyond a few dozen milliseconds, and is generally followed by ten times that in DOM updating, layout, and paint. If I’ve got a site that’s taking longer than this, I’d be asking questions about why I have so much data in the browser and so much DOM, rather than on which thread I should do my processing.

So the question we’re faced with is the same one from above: the user tapped something on the screen, we’re going to work on that request for hopefully less than a second, why would we want to make the screen responsive during that time?

OK what about the second scenario, where a store update isn’t in response to a user interaction? Performing an auto-save, for example — there’s nothing more annoying than an app becoming unresponsive doing something you didn’t ask it to do.

Actually there’s heaps of things more annoying than that. Teens, for example.

Anyhoo, if you’re doing an auto-save and taking 100ms to process data client-side before sending it off to a server, then you should absolutely use a Web Worker.

In fact, any ‘background’ task that the user hasn’t asked for, or isn’t waiting for, is a good candidate for moving to a Web Worker.

The matter of value

Complexity is expensive, and implementing Web Workers ain’t cheap.

If you’re using a bundler — and you are — you’ll have a lot of reading to do, and probably npm packages to install. If you’ve got a create-react-app app, prepare to eject (and put aside two days twice a year to update 30 different packages when the next version of Babel/Redux/React/ESLint comes out).

Also, if you want to share anything fancier than plain data between a worker and the main thread you’ve got some more reading to do (comlink is your friend).

What I’m getting at is this: if the benefit is real, but minimal, then you’ve gotta ask if there’s something else you could spend a day or two on with a greater benefit to your users.

This thinking is true of everything, of course, but I’ve found that Web Workers have a particularly poor benefit-to-effort ratio.

Hey David, why you hate Web Workers so bad?

Good question.

This is a doweling jig:

I own a doweling jig. I love my doweling jig. If I need to drill a hole into the end of a piece of wood and ensure that it’s perfectly perpendicular to the surface, I use my doweling jig.

But I don’t use it to eat breakfast. For that I use a spoon.

Four years ago I was working on some fancy animations. They looked slick on a fast device, but janky on a slow one. So I wrote fireball-js, which executes a rudimentary performance benchmark on the user’s device and returns a score, allowing me to run my animations only on devices that would render them smoothly.

Where’s the best spot to run some CPU intensive code that the user didn’t request? On a different thread, of course. A Web Worker was the correct tool for the job.

Fast forward to 2019 and you’ll find me writing a routing algorithm for a mapping application. This requires parsing a big fat GeoJSON map into a collection of nodes and edges, to be used when a user asks for directions. The processing isn’t in response to a user request and the user isn’t waiting on it. And so, a Web Worker is the correct tool for the job.

It was only when doing this that it dawned on me: in the intervening quartet of years, I have seen exactly zero other instances where Web Workers would have improved the user experience.

Contrast this with a recent resurgence in Web Worker wonderment, and combine that contrast with the fact that I couldn’t think of anything else to write about, then concatenate that combined contrast with my contrarian character and you’ve got yourself a blog post telling you that maybe Web Workers are a teeny-tiny bit overhyped.

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading

An Introduction to Web Workers

JavaScript Web Workers: A Beginner’s Guide

Using Web Workers to Real-time Processing

How to use Web Workers in Angular app

Using Web Workers with Angular CLI


Why ReactJS is better for Web Application Development?

Why ReactJS is better for Web Application Development?

Web Application Development is the point of contact for a business in today's digital era. It is important to choose the right platform for Web Application Development to build a high end Web

Web Application Development is essential for a business in today’s digital era. Finding the right platform for Web Application Development is important for building an effective Web Application that can enhance the overall customer engagement. Here’s what makes ReactJS a better option for building your next Web Application.