React Js Input Field White / Empty Spaces Validation Tutorial

Last updated on: by Editorial Team

React Js empty spaces validation tutorial; In this quick guide, you will learn how to remove white spaces and empty spaces from the form input field in React js application using regular expressions.

A regular expression is a collection of characters that defines a search pattern; it is ideally used to search a particular pattern in a string and performs “find” or “find and replace” operations on strings or input validation.

We will create a small component including an input field which will help us check if there is a white or empty space in an input field and display the error message to the user.

How to Add White Spaces and Empty Spaces Validation in an Input Filed in React Js

  • Step 1: Create React Project
  • Step 2: Create Component File
  • Step 3: No Space Validation
  • Step 4: Update App Js File
  • Step 5: Start React App

Create React Project

Create React app provides an easy-to-use environment for react development; let us go through the best way to install a new react app.

npx create-react-app react-blog

App is installed, next step is to get inside project directory.

cd react-blog

Create Component File

React allows managing your app in smaller chunks, you need to create a components/ folder; within this directory all the components code go.

Also, create a new FormComponent.js file, add the give code in the file.

import React, { Component } from "react";

class UrlComponent extends Component {
  render() {
    return (
      <div> </div>
    );
  }
}

export default UrlComponent;

No Space Validation in React

In this step, you have to open the components/FormComponent.js file and insert the given below code.

import React, { Component } from "react";

class FormComponent extends Component {
  state = {
    stringVal: "",
    isValid: false
  };

  stringValPatternValidation = stringVal => {
    return /\s/g.test(stringVal);
  };

  changestringVal = event => {
    const { value } = event.target;
    const isValid = this.stringValPatternValidation(value);

    this.setState({
      stringVal: value,
      isValid
    });

    console.log(this.stringValPatternValidation(value))
  };

  onSubmit = () => {
    const { stringVal } = this.state;
    console.log("Val: ", stringVal);
  };

  render() {
    const { isValid, stringVal } = this.state;
    return (
      <div>
        <form>
          <input
            type="text"
            name="stringVal"
            value={stringVal}
            onChange={this.changestringVal}
          />
          {this.state.isValid && (
            <div style={{ color: "#F61C04" }}>White or empty space is not allowed.</div>
          )}
          <button onClick={this.onSubmit}>Store</button>
        </form>

      </div>
    );
  }
}

export default FormComponent;

Update App Js File

Now, you have to add the FormComponent in the main app js file. Hence, open the src/App.js and update the following code inside the file.

import React from 'react';
import './App.css';

import FormComponent from './components/FormComponent';

function App() {
  return (
    <div className="App">
      <FormComponent />
    </div>
  );
}

export default App;

Start React App

Eventually, time has come to view the app in the browser, it requires you to start the development server using the mentioned below command.

npm start

After running the development server, you can view the application on the browser:

http://localhost:3000

React Js Input Field White / Empty Spaces Validation Tutorial

Conclusion

In this tutorial, we looked at how to easily implement empty or white space validation in a React input field using the regular expression.

You can use the suggested technique to inform the user to throw an error message if the white and empty space is found in the input field.