Form Validation Using React Examples

Today, We want to share with you Form Validation Using React Examples.In this post we will show you Simple React Form Validation, hear for react form validation library we will give you demo and example for implement.In this post, we will learn about react form validation best practices with an example.

Form Validation Using React Examples

There are the Following The simple About Form Validation Using React Examples Full Information With Example and source code.

As I will cover this Post with live Working example to develop simple form validation using react js, so the How to Set Up Basic React Form Validation in Two Minutes for this example is following below.

React Form Validation Example

Step 1: HTML Part

<div id="app"></div>

Step 2: JavaScript Part

const inputParsers = {
  date(input) {
    const split = input.split('/');
    const day = split[1]
    const month = split[0];
    const year = split[2];
    return `${year}-${month}-${day}`;
  },
  uppercase(input) {
    return input.toUpperCase();
  },
  number(input) {
    return parseFloat(input);
  },
};

class ShakingError extends React.Component {
	constructor() { super(); this.state = { key: 0 }; }

	componentWillReceiveProps() {
  	this.setState({ key: ++this.state.key });
  }
  
  render() {
  	return <div key={this.state.key} className="bounce">{this.props.text}</div>;
  }
}

class MyForm extends React.Component {
  constructor() {
    super();
    this.state = {};
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleSubmit(event) {
    event.preventDefault();
    if (!event.target.checkValidity()) {
    	this.setState({
        invalid: true,
        errors_live: true,
      });
      return;
    }
    const form = event.target;
    const data = new FormData(form);

    for (let name of data.keys()) {
      const input = form.elements[name];
      const parserName = input.dataset.parse;
      console.log('parser name is', parserName);
      if (parserName) {
        const parsedValue = inputParsers[parserName](data.get(name))
        data.set(name, parsedValue);
      }
    }
    
    this.setState({
    	res: stringifyFormData(data),
      invalid: false,
      errors_live: false,
    });

  }

  render() {
  	const { res, invalid, errors_live } = this.state;
    return (
    	<div>
        <form
          onSubmit={this.handleSubmit}
          noValidate
          className={errors_live ? 'errors_live' : ''}
         >
          <label htmlFor="membername">Member Name:</label>
          <input
            id="membername"
            name="membername"
            type="text"
            data-parse="uppercase"
          />

          <label htmlFor="email">Email:</label>
          <input id="email" name="email" type="email" required />

          <label htmlFor="happybday">Birthdate:</label>
          <input
            id="happybday"
            name="happybday"
            type="text"
            data-parse="date"
            placeholder="MM/DD//YYYY"
            pattern="\d{2}\/\d{2}/\d{4}"
            required
          />

          <button>Send data!</button>
        </form>
        
        
        
        <div className="res-block">
          {invalid && (
            <ShakingError text="Form is not valid" />
          )}
          {!invalid && res && (
          	<div>
              <h3>Transformed data to be sent:</h3>
              <pre>FormData {res}</pre>
          	</div>
          )}
        </div>
    	</div>
    );
  }
}

ReactDOM.render(
	<MyForm />,
  document.getElementById('app')
);


function stringifyFormData(fd) {
  const data = {};
	for (let key of fd.keys()) {
  	data[key] = fd.get(key);
  }
  return JSON.stringify(data, null, 2);
}

Step 3: CSS Part

body {
  font-family: 'Roboto Slab', sans-serif;
  background: white;
  color: #484848;
  padding: 40px;
}

input {
  display: block;
  margin-bottom: 15px;
  margin-top: 5px;
  padding: 10px;
  border: 1px solid #cfcfcf;
  font-family: 'Roboto Slab', sans-serif;
  font-size: 16px;
  outline: none;
}

.errors_live input:invalid {
  border-color: #f73772;
}

pre, code {
  font-family: 'Roboto Mono', Monaco;
}

button {
  cursor: pointer;
  padding: 12px;
  background: #999;
  font-family: 'Roboto Slab', sans-serif;
  font-size: 16px;
  border: none;
  outline: none;
  color: white;
  border-bottom: 2px solid #797979;
  
  &:hover {
    background-color: #a1a1a1;
  }

  &:active {
    background-color: #888;
  }
}

form {
  display: inline-block;
  margin-right: 50px;
  margin-bottom: 20px;
  vertical-align: top;
}

.res-block {
  display: inline-block;
}

h3 {
  margin-top: 0;
}

@keyframes bounce {
  from, 20%, 53%, 80%, to {
    animation-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
    transform: translate3d(0,0,0);
  }

  40%, 43% {
    animation-timing-function: cubic-bezier(0.755, 0.050, 0.855, 0.060);
    transform: translate3d(0, -30px, 0);
  }

  70% {
    animation-timing-function: cubic-bezier(0.755, 0.050, 0.855, 0.060);
    transform: translate3d(0, -15px, 0);
  }

  90% {
    transform: translate3d(0,-4px,0);
  }
}

.bounce {
  animation: bounce 0.5s;
  transform-origin: center bottom;
}

React Form Validation Tutorial
Web Programming Tutorials Example with Demo

Read :

Summary

You can also read about AngularJS, ASP.NET, VueJs, PHP.

I hope you get an idea about Form Validation Using React Examples.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.


Related FAQ

Here are some more FAQ related to this Article:

  1.   Modal Popup Form Submit in Ajax with PHP and Mysql
  2.   Simple PHP Shopping Cart
  3.   Laravel 6 Group By using Eloquent
  4.   Redirect page after delay using Angularjs Example
  5.   $interval Service using Angular Example
  6.   Google API Line Chart with JSON PHP & Mysql
  7.   Reactjs Form Validation Example with Demo
  8.   Laravel Global Variables Example Tutorial From Scratch
  9.   JQuery Push Key And Value Into An Array
  10.   PHP Laravel 5 Class Form HTML not found Resolve Error