Beginning React with Hooks by Lim Greg

Beginning React with Hooks by Lim Greg

Author:Lim, Greg [Lim, Greg]
Language: eng
Format: epub, azw3
Published: 2020-05-21T16:00:00+00:00


So you see how you can extend your application with more validation checks?

Implementing Custom Validation Exercise

In the previous example, we illustrated how to add custom validation capabilities to our application’s form to fulfill our needs i.e. a valid email cannot be less than 6 characters.

As an exercise, can you try doing checking for specific validation cases for password and showing the custom error message on your own? If you meet with any errors, just refer to the source code at the end of the chapter.

Clearing the Fields Upon Sucessful Submit

Currently, after submitting our forms, the user-entered values in the fields remain. They should be cleared out after submission. To do so, in handleSubmit , after successful validation, we clear the email and password state:

const handleSubmit = event => {

event.preventDefault();

if(emailValid && passwordValid){

alert('Email: ' + email + '\nPassword: ' + password);

setEmail("");

setPassword("");

}

}

This still however doesn’t clear our fields. We have to actually bind these state values to our fields’ values:

<Form.Control

type="email"

placeholder="Enter email"

onChange={event => setEmail(event.target.value)}

value={email}

/>

<Form.Control

type="password"

placeholder="Password"

onChange={event => setPassword(event.target.value)}

value={password}

/>

Now, when you run your app again and submit the form, because the field values are binded to the state’s, the fields will be cleared out.

Exercise

Note that we have completed our login form, try to come up with your own form and have additional inputs like text-areas, check boxes, radio buttons and more. The markup for them is available at https://react-bootstrap.netlify.app/ . They all work similar to the input fields that we have gone through.

Complete Code

We have covered a lot about React Forms in this chapter. Below lists the complete code for UserForm.js which is also available in my React GitHub repository (https://github.com/greglim81/react-hooks-chapter6 ).

import React, {useState} from 'react';

import {Form, Button, Alert} from 'react-bootstrap'

function UserForm() {

const [email, setEmail] = useState("")

const [password, setPassword] = useState("")

const [emailError, setEmailError] = useState("")

const [passwordError, setPasswordError] = useState("")

const handleSubmit = event => {

event.preventDefault();

var emailValid = false;

if(email.length == 0){

setEmailError("Email is required");

}

else if(email.length < 6){

setEmailError("Email should be minimum 6 characters");

}

else if(email.indexOf(' ') >= 0){

setEmailError('Email cannot contain spaces');

}

else{

setEmailError("")

emailValid = true

}

var passwordValid = false;

if(password.length == 0){

setPasswordError("Password is required");

}

else if(password.length < 6){

setPasswordError("Password should be minimum 6 characters");

}

else if(password.indexOf(' ') >= 0){

setPasswordError('Password cannot contain spaces');

}

else{

setPasswordError("")

passwordValid = true

}

if(emailValid && passwordValid){

alert('Email: ' + email + '\nPassword: ' + password);

setEmail("");

setPassword("");

}

}

return (

<div>

<Form onSubmit={handleSubmit}>

<Form.Group controlId="formBasicEmail">

<Form.Label>Email address</Form.Label>

<Form.Control type="email" placeholder="Enter email" onChange={event => setEmail(event.target.value)} value={email}/>

<Form.Text className="text-muted">

We'll never share your email with anyone else.

</Form.Text>

</Form.Group>

{emailError.length > 0 &&

<Alert variant="danger">{emailError}</Alert>}

<Form.Group controlId="formBasicPassword">

<Form.Label>Password</Form.Label>

<Form.Control type="password" placeholder="Password" onChange={event => setPassword(event.target.value)} value={password}/>

</Form.Group>

{passwordError.length > 0 &&

<Alert variant="danger">{passwordError}</Alert>}

<Button variant="primary" type="submit">

Submit

</Button>

</Form>

Email entered: {email}

<br />

Password entered: {password}

</div>

);

}

export default UserForm;

Summary

In this chapter, we learnt how to create a form with React Hooks. We created an initial JSX form with template from react-bootstrap . We then learned how to use Form.Group , Form.Control elements with onChange methods to handle form inputs, show form specific form field validation errors and how to validate the form upon submit.

Now after submitting a form, we need to persist the data by calling the API endpoint of the server. We will begin to explore on how to communicate with the server in the next chapter.

Visit my GitHub repository at https://github.com/greglim81/react-hooks-chapter6 if you have not already have the full source code for this chapter.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.