ReactJS input type url form validation Regular expression example


In this tutorial, you will learn how do input type url form validation in reactjs application.

You can see the full code on Github

Other versions available:

We will create react application using create-react-app tool to run application

npx create-react-app react-input-form

Now, let’s run the application

cd react-input-form
npm run start

This will starts application and open localhost:3000

Input type url regular expression validation in reactjs

This example explains about valid website url’s on change event handlers.

Here are steps for adding validation

  • Create a component folder in src folder
  • Lets create a Form a component named as InputUrlComponent
  • Add form element inside a render function
  • Create <input> element with type=url inside form
  • Create a button to handle submit functionality
  • Attach onChange bind event to input element
  • Create a two variables websiteurl for holding input url, isValid value to check validation succesful or not.
  • create a state object and initialize default values for websiteurl and isValid=false inside a constructor of a form component as seen below
    constructor(props) {
        super(props);
        this.state = {
            websiteUrl: "",
             isValid: false
        }
    }
    
  • form input value is bounded to the state values as seen below
<input  type="text" name="websiteUrl" value={websiteUrl}
  • we need to handle the user entered data on input field, Otherwise, typed data not shown, So added onChange event handler with `changeUrl' function
onChange={this.changeUrl}
  • OnChange handler in react being called while user typing the text. This will call changeUrl function defined as follows
  changeUrl = e => {
    const { value } = e.target;
    const isValid = !value || this.validateWebsiteUrl(value);

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

This saves the entered url value and checks validation logic, stores the validation result as well as entered url.

  • Let’s define the validation logic for url
    validateWebsiteUrl = websiteUrl => {
    const urlRegEx =
      '[-a-zA-Z0-9@:%_+.~#?&//=]{2,256}(.[a-z]{2,4})?\b(/[-a-zA-Z0-9@:%_+.~#?&//=]*)?';
    return urlRegEx.test(String(websiteUrl).toLowerCase());
  };

Defined regular expression pattern for URL This will check websiteUrl against regular expression using test method return true, if url is valid,else false

  • Displayed error text in red colour if isValid=false
  • Disabled if entered URL is invalid

Complete code for handing input type form validation

import React, { Component } from "react";

class InputUrlComponent extends Component {
  state = {
    websiteUrl: "",
    isValid: false
  };

  validateWebsiteUrl = websiteUrl => {
    const urlRegEx =
      '[-a-zA-Z0-9@:%_+.~#?&//=]{2,256}(.[a-z]{2,4})?\b(/[-a-zA-Z0-9@:%_+.~#?&//=]*)?';
    return urlRegEx.test(String(websiteUrl).toLowerCase());
  };

  changeUrl = e => {
    const { value } = e.target;
    const isValid = !value || this.validateWebsiteUrl(value);

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

  submitForm = () => {
    const { websiteUrl } = this.state;
    console.log("Website URL", websiteUrl);
  };

  render() {
    const { isValid, websiteUrl } = this.state;
    return (
      <div className="App">

        <form>
          <input
            type="text"
            name="websiteUrl"
            value={websiteUrl}
            onChange={this.changeUrl}
          />
          {!this.state.isValid && (
            <div style={{ color: "red" }}>URL is invalid</div>
          )}
          <br></br>
          <button onClick={this.submitForm} disabled={!isValid}>
            Submit
          </button>
        </form>

      </div>
    );
  }
}
export default InputUrlComponent;

InputUrlcomponent is called in App.js, here is file.

import "./App.css";
import InputUrl from './components/Input-url';

function App() {
  return (
    <div className="App">
      <h1>React Input type url pattern validation example</h1>
      <InputUrl />
    </div>
  );
}
export default App;

Here is the output you seen in the screen.

React Input type url form validation example
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.