Nina Diana

Nina Diana

1561165926

Validating a Login Form With React

For almost every form that you create, you will want some sort of validation. In React, 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

TLDR

  • Create a React 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 React 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 = () => (
  
    # Validated Form Component

  
);

export default ValidatedLoginForm;

Then, include it in your index.js file.

function App() {
  return (
    
      
    
  );
}

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);
  }}
>
  # Validated Login Form


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 (
        
          # Validated Login Form

        
      );
    }}

Display the 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 (
        
          Email
          

          Password
          <input
            name="password"
            type="password"
            placeholder="Enter your password"
          />
          
            Login
          
        
      );
    }}

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.

  
      Login
  

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 < 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 < 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.

Email
<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 && (
  {errors.email}

)}

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.

Password
<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 && (
  {errors.password}

)}

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!

30s ad

Master ReactJS: Learn React JS from Scratch

Learn ReactJS: Code Like A Facebook Developer

ReactJS Course: Learn JavaScript Library Used by Facebook&IG

React: Learn ReactJS Fundamentals for Front-End Developers

#reactjs #javascript

What is GEEK

Buddha Community

Validating a Login Form With React
Autumn  Blick

Autumn Blick

1598839687

How native is React Native? | React Native vs Native App Development

If you are undertaking a mobile app development for your start-up or enterprise, you are likely wondering whether to use React Native. As a popular development framework, React Native helps you to develop near-native mobile apps. However, you are probably also wondering how close you can get to a native app by using React Native. How native is React Native?

In the article, we discuss the similarities between native mobile development and development using React Native. We also touch upon where they differ and how to bridge the gaps. Read on.

A brief introduction to React Native

Let’s briefly set the context first. We will briefly touch upon what React Native is and how it differs from earlier hybrid frameworks.

React Native is a popular JavaScript framework that Facebook has created. You can use this open-source framework to code natively rendering Android and iOS mobile apps. You can use it to develop web apps too.

Facebook has developed React Native based on React, its JavaScript library. The first release of React Native came in March 2015. At the time of writing this article, the latest stable release of React Native is 0.62.0, and it was released in March 2020.

Although relatively new, React Native has acquired a high degree of popularity. The “Stack Overflow Developer Survey 2019” report identifies it as the 8th most loved framework. Facebook, Walmart, and Bloomberg are some of the top companies that use React Native.

The popularity of React Native comes from its advantages. Some of its advantages are as follows:

  • Performance: It delivers optimal performance.
  • Cross-platform development: You can develop both Android and iOS apps with it. The reuse of code expedites development and reduces costs.
  • UI design: React Native enables you to design simple and responsive UI for your mobile app.
  • 3rd party plugins: This framework supports 3rd party plugins.
  • Developer community: A vibrant community of developers support React Native.

Why React Native is fundamentally different from earlier hybrid frameworks

Are you wondering whether React Native is just another of those hybrid frameworks like Ionic or Cordova? It’s not! React Native is fundamentally different from these earlier hybrid frameworks.

React Native is very close to native. Consider the following aspects as described on the React Native website:

  • Access to many native platforms features: The primitives of React Native render to native platform UI. This means that your React Native app will use many native platform APIs as native apps would do.
  • Near-native user experience: React Native provides several native components, and these are platform agnostic.
  • The ease of accessing native APIs: React Native uses a declarative UI paradigm. This enables React Native to interact easily with native platform APIs since React Native wraps existing native code.

Due to these factors, React Native offers many more advantages compared to those earlier hybrid frameworks. We now review them.

#android app #frontend #ios app #mobile app development #benefits of react native #is react native good for mobile app development #native vs #pros and cons of react native #react mobile development #react native development #react native experience #react native framework #react native ios vs android #react native pros and cons #react native vs android #react native vs native #react native vs native performance #react vs native #why react native #why use react native

Yogi Gurjar

1600308055

Laravel 8 Form Validation Tutorial

Laravel 8 form validation example. In this tutorial, i will show you how to submit form with validation in laravel 8.

And you will learn how to store form data in laravel 8. Also validate form data before store to db.

How to Validate Form Data in Laravel 8

  1. Step 1 – Install Laravel 8 Application
  2. Step 2 – Configuring Database using Env File
  3. Step 3 – Create Model & Migration File For Form
  4. Step 4 – Create Routes
  5. Step 5 – Creating Controller
  6. Step 6 – Create Blade File For Form
  7. Step 7 – Start Development Server
  8. Step 8 – Run Laravel 8 Form Validation App On Browser

https://laratutorials.com/laravel-8-form-validation-example-tutorial/

#laravel 8 form validation #laravel 8 form validation tutorial #laravel 8 form validation - google search #how to validate form data in laravel 8 #form validation in laravel 8

Hayden Slater

1599277908

Validating React Forms With React-Hook-Form

Validating inputs is very often required. For example, when you want to make sure two passwords inputs are the same, an email input should in fact be an email or that the input is not too long. This is can be easily done using React Hook From. In this article, I will show you how.

Required Fields

The most simple, yet very common, validation is to make sure that an input component contains input from the user. React Hook Form basic concept is to register input tags to the form by passing register() to the tag’s ref attribute. As we can see here:

#react-native #react #react-hook-form #react-hook

Laravel 8 Form Validation Example

In this tutorial we will see laravel 8 form validation example, form validation in laravel is very common functionalities and it is use in each and every website to validate form field.

Here, We will use has function in session to check error message in laravel 8. using this example you can check simple form validation as well as you can create your own custom validation in laravel 8.

Laravel 8 Form Validation Example

https://websolutionstuff.com/post/laravel-8-form-validation-example


Read Also : Laravel 8 CRUD Operation Example

https://websolutionstuff.com/post/laravel-8-crud-operation-example

#laravel 8 form validation example #form validation #how to validate form in laravel 8 #form validation in laravel #laravel #laravel8

I am Developer

1626836644

React Google Login Example

Integrate google login in react apps; This example tutorial will show you step by step how to implement google login in react apps using javascript SDK.

If you want to integrate google login authentication in your react app. So you will not need any react plugin for this. In this tutorial, you will learn how to add a google login button in react app without any react plugin.

Before you can integrate Google Sign-In into your react app, you must create a client ID, which you need to call the sign-in API.

To create a Google API Console project and client ID, go to the APIs & Services dashboard and then follow the following steps:

Step 1: Visit Google Developer Console. And create a new project as following in below picture:

Step 2: you will see the screen looks like, show here you can set your project name as you want.

Step 3: Now you have successfully created a new project. After that, you need to select the created projects on the top menu. Then click on OAuth consent screen and select the given option according to your requirement:

Step 4: when you will be done above. After that automatically appear below given screen. In this screen, you need to fill your website URL, privacy policy URL, etc.

Step 5: you need to click on left side menu credentials and appear below screen. In this screen, you need to select OAuth client ID.

Step 6: After that, the below form will be apper. Here From different Application type options, you have to select Web application. Once you have select Web application option, then one form will appear on web page. Here you have to define Name and you have also define Authorized redirect URIs field and lastly click on Create button.

Step 7: the pop looks like below in picture automatically appear. Once you have click on the create button, then you can get your Client ID and your client secret key. You have to copy both key for future use for implement Login using Google account using PHP.

Please note that, google client id and secret.

How to Add Google Login to your React Apps

  • Step 1 - Create React App
  • Step 2 - Install Bootstrap 4 Library
  • Step 3 - Create Google Login Component
  • Step 4 - Import Google Login Component in App.js

https://www.tutsmake.com/react-google-login-button-example/

#react-google-login component #react-google-login demo #google login with react #add google login button to react