0

I created a user login using my Reusable Input Component. I having an issue with how I can implement my validation using react-hook-form 6.

login.js

const { register, handleSubmit, errors } = useForm({
    mode: 'onSubmit',
    reValidateMode: 'onClick',
    defaultValues: {
      username: '',
      password: '',
    }
  });

<form
        noValidate
        onSubmit={handleSubmit(onSubmit)}
      >
        <InputField
          type='text'
          placeholder='Email or Username'
          name='username'
          value={userInfo.username}
          onChange={handleChange}
          inputRef={register({
            required: 'You must provide a title.',
          })}
        />
        {errors.username && (
          <span className='text-red-900'>{errors.username.message}</span>
        )}
        <Button type='submit' caption='Sign In' />
      </form>

components/InputField.js

const InputField = ({ value, label, name, placeholder, type, onChange }) => (
  <div className='form-group w-full'>
    {label && <label htmlFor='input-field'>{label}</label>}
    <input
      type={type}
      value={value}
      name={name}
      className='bg-customBlack-light w-full text-xs p-4 mb-6 rounded-md outline-none transition duration-150 ease-in-out'
      placeholder={placeholder}
      onChange={onChange}
    />
  </div>
);

2 Answers 2

1
import React, { useState } from 'react";

const Login = () => {
    const [errors, setErrors] = useState({});
    const [userInfo, setUserInfo] = useState({});

    const handleSubmit = () => {
    if(!userInfo.username || userInfo.username.length === 0){
            errors["username"] = {
                isError: true,
                message: "Enter User Name"
            }
            setErrors{...errors};
        }
    };

    const handleChange = (e) => {
        // set userInfo state
        userInfo["username"] = e.targe.value;
        setUserInfo({...userInfo});

        // clear the userName error
        errors["username"] = {};
        setErrors{...errors};
    };

    return(
        <form
            noValidate
            onSubmit={handleSubmit(onSubmit)}
        >
            <InputField
                type='text'
                placeholder='Email or Username'
                name='username'
                value={userInfo.username}
                onChange={handleChange}
                inputRef={register({
                    required: 'You must provide a title.',
                })}
            />
            {errors.username && errors.username.isError && (
                <span className='text-red-900'>{errors.username.message}</span>
            )}
            <Button type='submit' caption='Sign In' />
        </form>
    );
}
Sign up to request clarification or add additional context in comments.

Comments

0

This is a simple example:

import React from "react";
import { useForm } from "react-hook-form";

export default function App() {
  const { register, handleSubmit } = useForm();
  const onSubmit = data => console.log(data);
   
  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input {...register("firstName", { required: true, maxLength: 20 })} />
      <input {...register("lastName", { pattern: /^[A-Za-z]+$/i })} />
      <input type="number" {...register("age", { min: 18, max: 99 })} />
      <input type="submit" />
    </form>
  );
}

You can see get more info from the react-hook-form documentation: https://react-hook-form.com/get-started

1 Comment

I'm using react-hook-form 6

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.