Controlling and Validating Forms

  • Controlled forms
  • Validating forms
  • Giving UI feedback

Controlled form

Now that our components are starting to look closer to what we would like, we should tie our form in with the state of our component. When people first start using Redux, they have a habit of tying everything into state. But just because you have the global store doesn't mean that everything belongs there. Or as Redux founder Dan Abramov said:

You don't need a single source of truth for everything. Just make sure you have a single source of truth for any particular thing.

A form like a signup or login form is a good example of transitory data that does not need to be saved in your Redux store. If a user navigates away and comes back, does he expect that Redux would remember the status of that form? Probably not. In fact, she would probably think it's weird.

It is for this reason that our Signup and Login components will have their values tied to local state. First we should set the initial values of our form state.

...
export class Signup extends React.Component {
constructor(props) {
super(props)
this.state = {
username: "",
email: "",
password: "",
passwordVerify: ""
}
this.submit = this.submit.bind(this)
}
...
}
...
export class Login extends React.Component {
constructor(props) {
super(props)
this.state = {
email: "",
password: ""
}
}
...
}

Update Login component

Then we need three more things. We need a handleChange function (or whatever you prefer to name it) that will update our state based on the input, we need to set the value of each input to the value of the corresponding state value, and we need to change the values that we submit to our new state values.

export class Login extends React.Component {
constructor(props) {
super(props)
this.state = {
email: "",
password: "",
}
this.submit = this.submit.bind(this)
}
submit() {
const user = {
email: this.state.email,
password: this.state.password,
}
this.props.dispatch(Actions.userLogin(user))
}
handleChange(input, e) {
this.setState({ [input]: e.target.value })
}
render() {
return (
<div className={style.wrapper}>
<div className={style.form}>
<div className={style.inputGroup}>
<input
value={this.state.email}
onChange={e => {
this.handleChange("email", e)
}}
placeholder="Email"
className={style.input}
type="text"
/>
</div>
<div className={style.inputGroup}>
<input
value={this.state.password}
onChange={e => {
this.handleChange("password", e)
}}
placeholder="Password"
className={style.input}
type="password"
/>
</div>
<Button onClick={this.submit} _style={{ width: "100%" }} type="primary">
Submit
</Button>
</div>
</div>
)
}
}

So now, when you type something into the input field, it triggers the onChange function, which in turn triggers the this.handleChange function that we defined. Within that function, we set the local state of the relevant input to the value of the input, which is also tied to the relevant this.state[value]. We've provided a handy chart showing the general flow of controlled forms below.

TODO image on form flow in React Handy chart coming soon

This might sound like a roundabout way of filling out forms, and that's because it is. But there are advantages of doing it this way (as you will see shortly).

Update Signup component

One things users have come to expect from forms is immediate feedback as to the validity of their form inputs because it's annoying to fill out an entire form only to submit the form and have an error telling you that it's invalid (especially when it then erases all existing form data, which many websites do for some reason).

Let's start by updating our Signup component to use a controlled form just like our Login component above.

export class Signup extends React.Component {
constructor(props) {
super(props)
this.state = {
username: "",
email: "",
password: "",
passwordVerify: "",
}
this.submit = this.submit.bind(this)
}
submit() {
const user = {
username: this.state.username,
email: this.state.email,
password: this.state.password,
}
this.props.dispatch(Actions.userNew(user))
}
handleChange(input, e) {
this.setState({ [input]: e.target.value })
}
render() {
return (
<div className={style.wrapper}>
<div className={style.form}>
<div className={style.inputGroup}>
<input
onChange={e => {
this.handleChange("username", e)
}}
value={this.state.username}
placeholder="Username"
className={style.input}
type="text"
/>
</div>
<div className={style.inputGroup}>
<input
onChange={e => {
this.handleChange("email", e)
}}
value={this.state.email}
placeholder="Email"
className={style.input}
type="text"
/>
</div>
<div className={style.inputGroup}>
<input
onChange={e => {
this.handleChange("password", e)
}}
value={this.state.password}
placeholder="Password"
className={style.input}
type="password"
/>
</div>
<div className={style.inputGroup}>
<input
onChange={e => {
this.handleChange("passwordVerify", e)
}}
value={this.state.passwordVerify}
placeholder="Verify Password"
className={style.input}
type="password"
/>
</div>
<Button onClick={this.submit} _style={{ width: "100%" }} type="primary">
Submit
</Button>
</div>
</div>
)
}
}

And now that we have a controlled form, we can use the values we received to validate our inputs before a user submits them. We're going to create two validations to make it easy for a user to know in advance whether the email address they entered is valid and whether the password match.

We'll start by creating valid and invalid constants that we can use as out inline style objects. If valid, the input will receive a green underline; if invalid, it will receive a red underline.

The first function is validatePassword, which compares the current state of our passwords and returns invalid if less than 6 characters or when the passwords don't match. It returns valid when the password are at least 6 characters and match.

The second is validateEmail, which uses a regular expression to make sure the email address contains an @ symbol, which is a bit oversimplified, but it servers our purposes.

...
const validInput = { borderBottom: "3px solid #4CAF50" }
const invalidInput = { borderBottom: "3px solid #F44336" }
export class Signup extends React.Component {
...
validateEmail() {
if (this.state.email.length < 1) return {}
return /@/.test(this.state.email) ? validInput : invalidInput
}
validatePassword() {
if (this.state.password.length < 1) return {}
if (this.state.password.length < 6) return invalidInput
return this.state.password === this.state.passwordVerify ? validInput : invalidInput
}
...
}

Then we need to connect these functions to our inputs. We're going to add a style tag to our email and passwordVerify inputs, and in that style tag we call the relevant function to validate. Note that in the event of no match (in both cases, if length is greater than 1), we're returning an empty object.

...
export class Signup extends React.Component {
...
render() {
return (
<div className={style.wrapper}>
<div className={style.form}>
...
<div className={style.inputGroup}>
<input
onChange={e => { this.handleChange("email", e) }}
style={this.validateEmail()}
value={this.state.email}
placeholder="Email"
className={style.input}
type="text" />
</div>
...
<div className={style.inputGroup}>
<input
onChange={e => { this.handleChange("passwordVerify", e) }}
style={this.validatePassword()}
value={this.state.passwordVerify}
placeholder="Verify Password"
className={style.input}
type="password" />
</div>
</div>
</div>
)
}
}

And now you have form validation. As you can see, React's inline styling makes this really easy.

Create validation endpoint to check if username/email is taken?

Previous: CRUD Endpoints for Organization: Part 1Next: CRUD Endpoints for Organization: Part 2