1

I have a form that I want to validate on one of the input and i use react hook form . This is the validation I want to apply:

const validateSheba=(str)=> {
    var pattern = /IR[0-9]{24}/;
    
    if (str.length !== 26) {
      return false;
    }
  
    if (!pattern.test(str)) {
      return false;
    }
  
    var newStr = str.substr(4);
    var d1 = str.charCodeAt(0) - 65 + 10;
    var d2 = str.charCodeAt(1) - 65 + 10;
    newStr += d1.toString() + d2.toString() + str.substr(2, 2);
    
    var remainder = this.iso7064Mod97_10(newStr);
    if (remainder !== 1) {
      return false;
    }
  
    return true;
  };

And that's how I used it:

                <Input
                name="Sheba"
                placeholder="Sheba"
                ref={register({
                    required: true,
                    pattern: {
                      value:value=> validateSheba(value),
                      message: "not valid",
                    },
                  })}
                  error={errors?.Sheba ? true : false}
                  helperText={errors?.Sheba?.message}
                inputClassName={classes.input}
              ></Input>

It does not work .. How should I do this?

3
  • Have you tried to change register({ ... }) to ...register({ ... })? Commented Jul 18, 2021 at 6:00
  • Yes, but it does not work Commented Jul 18, 2021 at 6:07
  • Could you please share executable code to stackbiltz or codesandbox? Commented Jul 18, 2021 at 6:16

2 Answers 2

2

The register method returns multiple values { onChange, onBlur, name, ref } that need to be registered with the input. E.g.

<Input {...register("test")} />

You assign the returned object to ref. I guess that is wrong, but I don't know how your Input component is implemented.

Here is an executable example. Just click Run code snippet at the bottom.

const { useState, useEffect, useContext, useRef, useMemo } = React;
const { useForm } = ReactHookForm;

const App = () => {
  const {
    register,
    handleSubmit,
    formState: { errors }
  } = useForm();

  const onSubmit = (data) => {
    alert(JSON.stringify(data));
  }; // your form submit function which will invoke after successful validation

  const nameRequired = errors.name && errors.name.type === "required";
  const namePattern = errors.name && errors.name.type === "pattern";

  const wrongAge = errors.age;

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <div className="form-group">
        <label>Name</label>
        <input
          {...register("name", {
            required: true,
            pattern: /^[A-Za-z]+$/i
          })}
          className="form-control"
        />
        {nameRequired && <p>This field is required</p>}
        {namePattern && <p>Alphabetical characters only</p>}
      </div>
      <div className="form-group">
        <label>Age</label>
        <input
          {...register("age", { min: 18, max: 99 })}
          className="form-control"
        />
        {wrongAge && (
          <p>You Must be older then 18 and younger then 99 years old</p>
        )}
      </div>
      <input type="submit" />
    </form>
  );
};

ReactDOM.render(<App />, document.getElementById("root"));
 <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<script src="https://unpkg.com/react/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/[email protected]/dist/index.umd.js"></script>
<div id="root"></div>

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

Comments

1

In your case, you are using a function for the validation, not a regex. The prop pattern is used for regex.

Please check this codesandbox example. https://codesandbox.io/s/react-hook-form-js-forked-5kep0?file=/src/App.js

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.