How to provide validation for react js form

How to provide validation for react js form.

I took a form with two fields. if two fields are enabled, you only need to enable the save button.

import React from 'react'
import { Button, Checkbox, Form } from 'semantic-ui-react'

const FormExampleForm = () => (
  <Form>
    <Form.Field>
      <label>First Name</label>
      <input placeholder='First Name' />
    </Form.Field>
    <Form.Field>
      <label>Last Name</label>
      <input placeholder='Last Name' />
    </Form.Field>
    <Form.Field>
      <Checkbox label='I agree to the Terms and Conditions' />
    </Form.Field>
    <Button type='submit'>Submit</Button>
  </Form>
)

export default FormExampleForm

      

+3


source to share


2 answers


In reduction forms 6.7 there is a simple property called pristine

which can be used for this. But if the user enters any value in at least one input field, the submit button is activated. To do this, you may need to do something like this.

  render() {
    // const { handleSubmit } = this.props;
    const {handleSubmit, pristine, reset, submitting} = this.props
    return (
      <form onSubmit={handleSubmit(this.onSubmit.bind(this))}>
        <div>
            <label>First Name</label>
            <div>
              <Field name="firstName" component="input" type="text" placeholder="First Name"/>
            </div>
        </div>
      <button type="submit" className="btn btn-primary" disabled={pristine || submitting}>Submit</button>
      </form>
    );
  }
}

      

But if you need to enable a submit button tell when the user enters values ​​in 2 given fields or so then it gets tricky. You need to do something like this. Here is my example usecase. The form has 3 fields firstName, lastName and age. The submit button is only activated if the user enters values ​​for the firstName and lastName input fields. Please see the following code.



import React, { Component } from 'react';
import { Field, reduxForm, formValueSelector } from 'redux-form';
import { connect } from 'react-redux';

class UserNew extends Component {
  constructor(props) {
    super(props);
    this.isSubmitEnabled = this.isSubmitEnabled.bind(this);
  }


  onSubmit(values) {
    console.log(values);
  }

  isSubmitEnabled() {
   // Access field values here and validate them
   const firstName = this.props.firstNameValue;
   const lastName = this.props.lastNameValue;
   if(firstName && lastName){
      return true;
   }
   return false;
 }

  render() {
    const { handleSubmit } = this.props;
    const isEnabled = this.isSubmitEnabled();


    return (
      <form onSubmit={handleSubmit(this.onSubmit.bind(this))}>
      <div>
        <label>First Name</label>
        <div>
          <Field name="firstName" component="input" type="text" />
        </div>
      </div>
      <div>
        <label>Last Name</label>
        <div>
          <Field name="lastName" component="input" type="text" />
        </div>
      </div>
      <div>
        <label>Age</label>
        <div>
          <Field name="age" component="input" type="text" />
        </div>
      </div>
      <button type="submit" className="btn btn-primary" disabled={!isEnabled}>Submit</button>
      </form>
    );
  }
}


UserNew = reduxForm({
  form: 'UserNewForm'
})(
  UserNew
);

// Decorate with connect to read form values
const selector = formValueSelector('UserNewForm') // <-- same as form name
UserNew = connect(state => {
  const firstNameValue = selector(state, 'firstName')
  const lastNameValue = selector(state, 'lastName')
  return {
    firstNameValue,
    lastNameValue,
  }
})(UserNew)


export default UserNew;

      

To access field values ​​you need to use formValueSelector

ReduxForms. To do this, you need to connect your form to the reduct store using a connect

helper.

Hope this helps. Happy coding!

+5


source


Alternatively, you can use Redux form, as not in the above code, so you can write your own JS validation code. For this you need to follow below



  • Initialization state in

    contructor(){
     this.state{
       first_name: null,
       last_name: null,
     }
    }
    
          

  • Change the state of each input element onChange onChange={()=>this.setState({first_name: event.target.value})}

  • Now add the onClick property to <Button onClick={this.handleSubmit} />

  • inside handleSubmit()

    you can get values ​​through the local state of the component and add validation rules like

    if (this.state.first_name == ") {console.log (" Enter name ")}

0


source







All Articles