,

React Tutorial: Validate White and Empty Spaces from Input Fields to Message

We will discuss how to implement white and empty space validation for form input fields in a React application. We will be doing this by using regular expressions which are a powerful tool for pattern matching in strings. In this article, we will create a sample component that not only detects white and empty spaces…

By.

•

min read

We will discuss how to implement white and empty space validation for form input fields in a React application. We will be doing this by using regular expressions which are a powerful tool for pattern matching in strings.

In this article, we will create a sample component that not only detects white and empty spaces but also displays an error message to the user.

Understanding Regular Expressions

A regular expression is a collection of characters that are used to defines a search pattern. This pattern is used to search for specific sequences within strings and can be deployed for tasks such as finding and replacing text or validating input. In our case we will detect empty or white spaces within the provided text in the input fields and throw a message for indication.

 

How to Add White and Empty Space Validation on Input Field?

Following are the steps for implementing the above-mentioned:

Step 1: Create React Project

Step 2: Create Component File

Step 3: Implement No Space Validation

Step 4: Update the App Js File

Step 5: Start React App

 

Step 1- Create React Project

In the very first step, we will install a React app by using create-react-app. It offers an easy-to-use environment for React project development. See below:

npx create-react-app react-blog

 

So, after installing the app, we will get inside the project directory:

cd react-blog

 

Step 2- Create Component File

Next we will start by creating a components directory within your project and then create a new file named FormComponent.js inside this directory. This file will have the following code for our input form component.

import React, { Component } from "react";

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

export default UrlComponent;

 

Step 3: Implement No Space Validation

Within the ~components/FormComponent.js file, we will implement the logic for validating input to ensure it does not contain any white or empty spaces. Update the FormComponent.js file with the following code to achieve this:

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;

 

Step 4- Update App Js File

Here, we have to add the FormComponent in the main app js file. Therefore, we will 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;

 

Step 5- Start the React App

Finally, it’s time to see your application in action. Launch the development server with the following command:

npm start

Conclusion

We have learned how to implement white and empty space validation for input fields in a React application using the of regular expressions. By creating a simple yet effective component, we have also added feedback to users about invalid input by showing them a custom message.

Hope this will be helpful!

Leave a Reply

Your email address will not be published. Required fields are marked *