0

I am trying to validate an onchange but can't seem to get it working.

Essentially, I want to test that if the input matches the regex then we present a message under the input.

I am unsure where to put the validator, I wondered if anyone could point me in the right direction

Here is a sandbox.

https://codesandbox.io/s/blazing-hooks-gni5jy?file=/src/components/Dashboard/Dashboard.js

const Dashboard = () => {
  const [number, setNumber] = useState(null);
  // const [isValid, setIsValid] = useState(false);

  // const validator = (value) => {
  //   if (!value) return false;
  //   const re = /\b\d{5}\b/g;
  //   return re.test(value.trim());
  // };

  const onChangeHandler = (event) => {
    const value = event.target.value;
    setNumber(value);
  };

  return (
    <div>
      <input value={number || ""} onChange={onChangeHandler} />
      {/* {isValid ? <p>is valid</p> : null} */}
    </div>
  );
};

export default Dashboard;

2 Answers 2

2

Set the state inside the validator

  const [isValid, setIsValid] = useState(true);

  const validator = (value) => {
    if (!value) return false;
    const re = /\b\d{5}\b/g;
    const valid = re.test(value);
    setIsValid(valid);
  };

  const onChangeHandler = (event) => {
    const value = event.target.value;
    setNumber(value);
    validator(value);
  };

Demo

Sign up to request clarification or add additional context in comments.

Comments

2

You will have to call the validator for it to work.

import React, { useState } from "react";

const Dashboard = () => {
  const [number, setNumber] = useState(null);
  const [isValid, setIsValid] = useState(false);

  const validator = (value) => {
    if (!value) return false;
    const re = /\b\d{5}\b/g;
    return re.test(value.trim());
  };

  const onChangeHandler = (event) => {
    const value = event.target.value;
    setNumber(value);
    setIsValid(validator(value)); // Validating the input
  };

  return (
    <div>
      <input value={number || ""} onChange={onChangeHandler} />
      {isValid ? <p>is valid</p> : null}
    </div>
  );
};

export default Dashboard;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.