user9458800
user9458800

Reputation:

Compare form values in react components at onSubmit or during changes?

I'm trying to compare 2 form components values like password and confirm password but it creates some problems.

Also suggest me to go with alert message or any new way to display the message that user will get some interactive message also.

When I put alert message in inputData function it always popping up and when I kept in submitData function it's not even checking it.

Here's my code:

 import React,{Component} from "react";
import {BrowserRouter as Router, Link, Switch, Route} from "react-router-dom";
class App extends Component {
  constructor(props){
    super(props);

    this.state = {
      password: '',
      c_password: '',
      isDone:false
    };
    this.inputData = this.inputData.bind(this);
    this.submitData = this.submitData.bind(this);
  }
  inputData(event)
  {
    if(this.state.password==this.state.c_password)
    {
      this.setState({
        [event.target.name]:event.target.value,
        isDone:true
      });
    }
    else if(this.state.password!=this.state.c_password)
    {
        this.setState({
          isDone:false
        });
    }
  }
  submitData(event)
  {
    if(this.state.isDone==false)
    {
      alert("Passwords don't match")
    }
    else if(this.state.isDone==true)
    {
      alert("Passwords matched");
    }
    event.preventDefault();
  }
  render(){
    return(
      <div>
        <form onSubmit={this.submitData}>
          Password:
          <input type="password" name="password" onChange={this.inputData}/>
          <input type="password" name="c_password" onChange={this.inputData}/>
          <button type="submit">Submit</button>
        </form>
      </div>
    );
  }
}
export default App;

When I execute it always shows don't match even if I write same password in both fields...!

Upvotes: 1

Views: 6590

Answers (2)

PassionInfinite
PassionInfinite

Reputation: 638

The above answer will work but we can do whole thing in one function. Also, we can utilise this function for many other fields. Initialize the isDone = false as default in the state. Then answer for the above question goes like this:

inputData(event) {
const field = event.target.name

this.setState({
  [field]: event.target.value
})

if (this.state.password === this.state.c_password) {
 this.setState({
  isDone: true
 })
}

Tip: 1) You can use anonymous functions like () => this.submitData() in the handler so that you don't need to bind the handler function with this in the constructor as this anonymous function preserves this. 2) For using forms efficiently you can use two popular libraries redux-form and react-form

This will help you to get good errors as well as clear your code.

Upvotes: 0

Omar
Omar

Reputation: 3411

import React, { Component } from "react";
import { render } from "react-dom";

class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      password: "",
      c_password: "",
    };

    this.submitData = this.submitData.bind(this);
  }
  inputPassword = event => {
    this.setState({ password: event.target.value });
  };

  confirmPassword = event => {
    this.setState({ c_password: event.target.value });
  };
  submitData(event) {
    event.preventDefault();
    const { password, c_password } = this.state;
    const matches = password === c_password;
    matches ? alert("MATCHED") : alert("NO MATCH");  
  }
  render() {
    return (
      <div>
        <form onSubmit={this.submitData}>
          Password:
          <input
            type="password"
            name="password"
            onChange={this.inputPassword}
          />
          <input
            type="password"
            name="c_password"
            onChange={this.confirmPassword}
          />
          <button type="submit">Submit</button>
        </form>
      </div>
    );
  }
}
export default App;

render(<App />, document.getElementById("root"));

if you want to do it with one function Declare byPropKey

 const byPropKey = (propertyName, value) => () => ({
  [propertyName]: value,
});

Now to use it the way you want.

<input value={this.state.password} onChange={event=> this.setState(byPropKey('password', event.target.value))} type="password" placeholder="Password" />
<input value={this.state.c_password} onChange={event=> this.setState(byPropKey('c_password', event.target.value))}

Upvotes: 1

Related Questions