hello world
hello world

Reputation: 1755

react enable button after all form fields are not empty

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

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

Upvotes: 4

Views: 21756

Answers (5)

Aiyegbajeje Yusuf
Aiyegbajeje Yusuf

Reputation: 1

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

Upvotes: 0

Johnson Samuel
Johnson Samuel

Reputation: 2076

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>
    );
  }
}

Upvotes: 2

Javad Khodadadi
Javad Khodadadi

Reputation: 408

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

Upvotes: -1

Lucas Milotich
Lucas Milotich

Reputation: 398

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 });
  }`

Upvotes: 1

Alex Dovzhanyn
Alex Dovzhanyn

Reputation: 1046

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.

Upvotes: 8

Related Questions