Validation of form input fields in React

react-form validation - npm
react form validation best practices
react form validation - stack overflow
react form validation hooks
react input touched
react-bootstrap form validation
react native input validation
field validation in react native
<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.

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' />

How to use HTML5 form validations with React, So we spend most of our times adding input field elements and code some validation checks on it which our work could get tedious and at times  We’re adding a property called formErrors which will be an object with the input field names as keys and any validation errors as their values. The initial value for each key is an empty string. The initial value for each key is an empty string.

with React hook, we can build custom hook to make validation much easier. with your example blow. you can easily by adding register method from react hook form: https://github.com/bluebill1049/react-hook-form

import React from 'react';
import useForm from 'react-hook-form';

function Test() {
  const { register, handleSubmit } = useForm();
  const onSubmit = data => console.log(data);

  return {
    <form className="form-group" onSubmit={handleSubmit(onSubmit)}>
      <label className="col-sm-0 control-label"> Name : &nbsp; </label>
        <input
          type="text"
          ref={register}
          placeholder="Name"
          pattern="[A-Za-z]{3}"
          className="form-control"
        /> 
     </div>
  }
}

Reactjs - Form input validation, You should avoid using refs, you can do it with onChange function. On every change, update the state for the changed field. Then you can easily check if that  Form validation is most important part in web development, through which we can restrict invalid entries and validate user details in some extent by using valid sets of checkpoints or validation rules.

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

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

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

Instant form field validation with React's controlled inputs, 03 Jan 2017. Instant form field validation with React's controlled inputs. If you've false means no errors aka entirely valid; true means a field is invalid. In future  This is for developers who don’t want to use and adopt any existing libraries because they create a black box in your form validation for React Apps alone. If that’s the case, you’ve come to the right place. This is for developers who don’t want too much setup in field validations,

react-inputs-validation, import React from "react"; import { Formik, Form, Field } from "formik"; function validateEmail(value) { let error; if (!value) { error = "Required"; } else if (!/^[A-Z0-9. Instant form field validation with React's controlled inputs 03 Jan 2017 If you’ve followed along, you know about controlled inputs and simple things they enable, like disabling the Submit button when some fields are missing or invalid.

Home, How to use React's controlled inputs for instant form field validation false means no errors or entirely valid; true means a field is invalid. Form Validation in React - Code Monkey - Medium Client-side validation is the process of checking that the values in your form’s input fields conform to certain expectations. Did the user fill out

How to use React's controlled inputs for instant form field validation, But we're not updating the state on user input, so if we type in the form fields now, our text won't appear. We need an onChange handler for the  Intuitive, feature-complete API providing a seamless experience to developers when building forms. Leverage existing HTML markup and validate your forms with our constraint-based validation API. Package size matters. React Hook Form is a tiny library without any dependencies. Minimizes the number of re-renders and faster mounting, striving to

Comments
  • No it's not validating for text which I input
  • what validation do u want? the regex i used validate whether its a character or not, it will not allow user to write any num. did u check the jsfiddle what is the issue in that?
  • hi its working for me now, i had done some mistake regarding variable.
  • Can u pls tell me how do I add popup or a comment if user tries to enter anything other than alphabets ?
  • since you are using reactjs, u can use the awesome Material-Ui components, check the snackbar, use it for showing the error: material-ui.com/#/components/snackbar