aniketh deokar
aniketh deokar

Reputation: 15

Regex Validation for userInput in React

import { useState } from "react";
import "./styles.css";
import { re, RegexParser } from "./regexValidation";

export default function App() {
  const [val, setVal] = useState("");
  const [validRegex, setValidRegex] = useState(false);

  const validateRegex = (val: string) => {
    setVal(val);
    if (val === "") {
      setValidRegex(false);
      return;
    }
    // to check if the entered value(val) is a valied regex in string
    if (re.test(val)) {
      setValidRegex(false);
      // parsing the entered value(val) to a regularexpression
      const convertToRegex = RegexParser(val);

      //filtering logic to filter based on convertToRegex variable
    } else {
      setValidRegex(true);
    }
  };
  const handleChange = (e: any) => {
    validateRegex(e.target.value);
  };
  return (
    <div className="App">
      <input value={val} onChange={handleChange}></input>
      <h1>{validRegex ? "inValidRegex" : "ValidRegex"}</h1>
    </div>
  );
}

Upvotes: 1

Views: 368

Answers (1)

mitchazj
mitchazj

Reputation: 556

This looks like it might be an incompatibility between the two libraries you are using (ie, they have different ideas of what valid Regex is).

Easiest way to fix this (and honestly the safest too, since you're dealing with user input) is to wrap your entire parsing logic with a try/catch like this:

// to check if the entered value(val) is a valied regex in string
if (re.test(val)) {
   let convertToRegex;
   try {
      convertToRegex = RegexParser(val);
      setValidRegex(true); // only set this AFTER a successful parse.
      // also note I've swapped the true / false value here.
   } catch (e) {
      setValidRegex(false);
   }

   if (convertToRegex) {
      // TODO: implement filtering logic based on convertToRegex variable
   }
} else {
   // NOTE: it didn't parse correctly, shouldn't this be false?
   setValidRegex(false); // I've changed it for you
}

Also I think(?) you've made a couple errors in how you're handling setValidRegex which I've corrected in code. Don't be optimistic and say the user input is valid regex when you haven't actually confirmed (by creating a RegexParser) that it is!

With this approach there's an argument for deleting the re.test(val) and the other library entirely since you can get what you want by simply try/catch-ing. Up to you to decide if this is a decent choice for your codebase.

Upvotes: 1

Related Questions