Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validation of form input fields in React

<div className="form-group">
  <label className="col-sm-0 control-label"> Name : &nbsp; </label>
  <input
    type="text"
    value={this.state.UserName}
    onChange={this.handleChangeUserName}
    placeholder="Name"
    pattern="[A-Za-z]{3}"
    className="form-control"
  />
</div>

Hi, I am trying to validate a form input field in React using pattern validation. But it's not working. I am using validation as simple as pattern="[A-Za-z]{3}".

Kindly let me know how to work this out. Putting validation in React Bootstrap component.

like image 534
developer_beginning Avatar asked Jan 30 '17 12:01

developer_beginning


People also ask

How do I validate a form in react?

To validate the field, you pass an object containing the validation function: Once you have a custom field component, you can now use the useForm Hook to validate your form. A simple React component that allows you to build and validate HTML forms using JSON schema. It ships with simple form validation by default.

How do I validate the values received in the input fields?

The values received in the input fields can be validated on the change event handler. We will be adding the following validations to the sign-up form: Note: The validations added here would be running on the client side.

How to validate input in react Bootstrap component?

Kindly let me know how to work this out. Putting validation in React Bootstrap component. You are using the value property (means controlled component) of input element and updating the state in onChange method, So you can easily test this regex in onChange and update the state only when the input will be valid.

What is Rc-field-form in react?

Simple React Validator weighs 4kB when minified and gzipped rc-field-form is a performant form component library that has strong TypeScript support. The documentation does not explain the this library’s usage in detail. You’ll have to understand the use cases from the examples. The <Form /> component is used to wrap the form input fields.


2 Answers

You are using the value property (means controlled component) of input element and updating the state in onChange method, So you can easily test this regex in onChange and update the state only when the input will be valid.

Like this:

handleChangeUserName(e){
   if(e.target.value.match("^[a-zA-Z ]*$") != null){
       this.setState({UserName: e.target.value});
   }
} 

Check the working code:

class HelloWidget extends React.Component {
  
  constructor(){
    super();
    this.state={UserName:''}
    this.handleChangeUserName = this.handleChangeUserName.bind(this);
  }
  
  handleChangeUserName(e){
    if(e.target.value.match("^[a-zA-Z ]*$")!=null) {
      this.setState({UserName: e.target.value});
    }
  }

  render(){
    return(
      <div className="form-group">
        <label className="col-sm-0 control-label" htmlFor="textinput"> Name : &nbsp; </label>
        <input type="text" value={this.state.UserName} onChange={this.handleChangeUserName}  placeholder="Name" className="form-control"></input>
      </div>
    )
  }
}
  
ReactDOM.render(<HelloWidget/>, document.getElementById('container'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='container' />

Check the jsfiddle for working example: https://jsfiddle.net/uL4fj4qL/11/

Check this jsfiddle, Material-Ui snackbar added to show the error, if user tries to enter the wrong value: https://jsfiddle.net/4zqwq1fj/

like image 126
Mayank Shukla Avatar answered Oct 01 '22 18:10

Mayank Shukla


pattern="[A-Za-z]{3}" is a feature from HTML5.

Complete solution here: https://codepen.io/tkrotoff/pen/qypXWZ?editors=0010

If you only want to use default HTML5 validation:

class FormValidate extends React.Component {
  state = {
    username: ''
  };

  handleUsernameChange = e => {
    console.log('handleUsernameChange()');
    this.setState({
      username: e.target.value
    });
  }

  handleSubmit = e => {
    console.log('handleSubmit() Submit form with state:', this.state);
    e.preventDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <div className="form-group">
          <label htmlFor="username">Name</label>
          <input
            id="username"
            name="username"
            value={this.state.username}
            onChange={this.handleUsernameChange}
            placeholder="Name"
            pattern="[A-Za-z]{3}"
            className="form-control" />
        </div>

        <button className="btn btn-primary">Submit</button>
      </form>
    );
  }
}

Invalid input FormValidate

If you want to better integrate with Bootstrap 4:

class FormNoValidate extends React.Component {
  state = {
    username: '',
    error: ''
  };

  handleUsernameChange = e => {
    console.log('handleUsernameChange()');
    const target = e.target;
    this.setState({
      username: target.value,
      error: target.validationMessage
    });
  }

  handleSubmit = e => {
    console.log('handleSubmit() Submit form with state:', this.state);
    e.preventDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit} noValidate>
        <div className="form-group">
          <label htmlFor="username">Name</label>
          <input
            id="username"
            name="username"
            value={this.state.username}
            onChange={this.handleUsernameChange}
            placeholder="Name"
            pattern="[A-Za-z]{3}"
            className="form-control" />
          <div className="invalid-feedback d-block">
            {this.state.error}
          </div>
        </div>

        <button className="btn btn-primary">Submit</button>
      </form>
    );
  }
}

Invalid input FormNoValidate

If you want to go further (more features, more control, better integration):

I've written a very simple React library to deal with form validation and that supports HTML5 attributes: https://github.com/tkrotoff/react-form-with-constraints

Examples here: https://github.com/tkrotoff/react-form-with-constraints/blob/master/README.md#examples

like image 30
tanguy_k Avatar answered Oct 01 '22 18:10

tanguy_k