4

hey guys new to react trying to achieve some simply validation but struggling. i want to

  • disable button if form fields are empty
  • enable button if ALL form fields are filled

i want to do all of this on the fly but been struggling/ cant find anything solid for a reference. here is my code

import React from 'react';
//import ReactDOM from 'react-dom';
import { Button, Form, FormGroup, Label, Input } from 'reactstrap';

export default class Forms extends React.Component {
  constructor() {
    super();
    this.state = {
      fname: '',
      lname: '',
      email: '',
      password: '',
      confirmPassword: '',
      formSuccess: false
    }
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleUserInput(e) {
    const name = e.target.name;
    const value = e.target.value;
    this.setState({ [name]: value });
  }

  handleSubmit(e) {
    e.preventDefault();
  }

  render() {
    return (
      <Form onSubmit={this.handleSubmit}>
        <FormGroup>
          <Label for="fname">First Name</Label>
          <Input
            value={this.state.fname}
            onChange={(event) => this.handleUserInput(event)}
            type="text"
            name="fname"
            id="fname"
            placeholder="first name"
          />
        </FormGroup>
        <FormGroup>
          <Label for="lname">Last Name</Label>
          <Input
            onChange={(event) => this.handleUserInput(event)}
            value={this.state.lname}
            type="text"
            name="lname"
            id="lname"
            placeholder="last name"
          />
        </FormGroup>
        <FormGroup>
          <Label for="email">Email</Label>
          <Input
            onChange={(event) => this.handleUserInput(event)}
            value={this.state.email}
            type="email"
            name="email"
            id="email"
            placeholder="email"
          />
        </FormGroup>
        <FormGroup>
          <Label for="password">Password</Label>
          <Input
            onChange={(event) => this.handleUserInput(event)}
            type="password"
            value={this.state.password}
            name="password"
            id="password"
            placeholder="password"
          />
        </FormGroup>
        <FormGroup>
          <Label for="confirmPassword">Confirm Password</Label>
          <Input
            onChange={(event) => this.handleUserInput(event)}
            value={this.state.confirmPassword}
            type="password"
            name="confirmPassword"
            id="confirmPassword"
            placeholder="confirm password"
          />
        </FormGroup>
        <FormGroup check>
          <Label check>
            <Input type="checkbox" />{' '}
            Check me out
        </Label>
        </FormGroup>
        <Button color="primary" size="lg" disabled={!this.state.formSuccess}>Submit</Button>
      </Form>
    )
  }
}

thanks for all the help

3
  • I dont see formSuccess value being anywhere. Do you want to disable the button if all fields are empty ? Commented May 25, 2018 at 4:25
  • @johnsam my goal is to only let the user submit the form when all fields are filled using formSuccess Commented May 25, 2018 at 4:27
  • please check the working codepen link and also the code I have shared :).. Let me know if that works. Commented May 25, 2018 at 6:32

5 Answers 5

8

Add a function to your component like so:

isFormValid = () => {
  const {fname, lname, email, password, confirmPassword} = this.state

  return fname && lname && email && password && confirmPassword
}

and then change your button to be:

<Button color="primary" size="lg" disabled={!this.isFormValid}>Submit</Button>

This way you don't even need the formSuccess in your state.

Sign up to request clarification or add additional context in comments.

9 Comments

hmm just tried your code and doesnt work like how i imagined
whats the issue?
can u post a codepen or something? im calling isFormValid() in my handleuserinput function
@helloworld Dont call isFormValid(), if you do so, it'll immediately execute the function once per component render. what you want to do is pass it in without the parentheses, like I did in my example above, and make note of the ! operator before the function call
@Ajay because it's not the code I deserve, but the one I need right now 🦇
|
2

Working codepen: https://codesandbox.io/s/yjn2zz4qvj

Code:

import React, { Component } from "react";

export default class Hello extends Component {
  state = {
    email: "",
    name: ""
  };

  handleChange = e => {
    const { value, name } = e.target;
    this.setState({ [name]: value });
  };

  render() {
    return (
      <div>
        <form className="col-md-5">
          <div className="form-group">
            <label> Email: </label>
            <input
              name="email"
              value={this.state.email}
              placeholder="email"
              onChange={this.handleChange}
            />{" "}
            <br />
          </div>
          <div className="form-group">
            <label> Name: </label>
            <input
              name="name"
              value={this.state.name}
              placeholder="name"
              onChange={this.handleChange}
            />
          </div>
          <button
            type="button"
            disabled={!this.state.email || !this.state.name}
          >
            Button
          </button>
        </form>
      </div>
    );
  }
}

1 Comment

can you elaborate on disabled={!this.state.email || !this.state.name} i thought react has issues updating the state? sorry if this a noob question, still learning react
1

You should have a state called isAvailable or something like this and you should use it in the button like this:

`<Button color="primary" size="lg" disabled={!this.state.isAvailable}>Submit</Button>`

And then, in the function handleUserInput you should update that state:

`handleUserInput(e) {
    const name = e.target.name;
    const value = e.target.value;
    this.setState({ name: value, isAvailable: true });
  }`

2 Comments

the button should only disable when all the form fields are field, your solution doesnt work...
What do you mean by 'all the form fields are field' ??
0

Here is an approach i used to clear off the issue to make sure all inputs are valid before the button enables

  const [firstName, setFirstName] = useState("");
  const [lastName, setLastName] = useState("");
  const [email, setEmail] = useState("");
const [password, setPassword] = useState({
    value: "",
    isTouched: false,
  });
  const [role, setRole] = useState("role");
  const [Valid, setValid] = useState(false);

  const getIsFormValid = () => {
    if (firstName && email && password?.length && validateEmail(email)) {
      setValid(true);
    } else {
      setValid(false);
      return false;
    }
  };
  
  return(
  
  
    <button type="submit" disabled={!Valid}>
            Create account
          </button>
  )
  
  

Comments

-1

You can use react-validation If all validation is true button is enable

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.