react-hook-form validation before submission

Viewed 20113

I have a form (sorry it is so long) that is very simple for a user to enter name, email, phone, comments:

    <form
        className={classes.root}
        data-testid="getting-started-form"
        onSubmit={handleSubmit(onSubmit)}
    >
        <div style={{ width: '400px' }}>
            <div style={{ width: '100%'}}>
                <Controller as={<TextField
                    label="Name"
                    id="name"
                    name="name"
                    type="text"
                    value={name}
                    placeholder="Name"
                    onChange={(e: React.FormEvent<EventTarget>) => {
                        let target = e.target as HTMLInputElement;
                        setName(target.value);
                    }}
                    inputProps={{
                        'data-testid': 'name'
                    }}
                />} name="name" rules={{ required: true }} control={control}
                />
                {errors.name && <span>Name is required</span>}
            </div>
            <div style={{ width: '100%' }}>
                <Controller as={<TextField
                    label="Email"
                    id="email"
                    name="email"
                    type="text"
                    value={email}
                    placeholder="Email"
                    style={{ width: '100%' }}
                    onChange={(e: React.FormEvent<EventTarget>) => {
                        let target = e.target as HTMLInputElement;
                        setEmail(target.value);
                    }}
                    inputProps={{
                        'data-testid': 'email'
                    }}
                />} name="email" rules={{ required: true, pattern: /^\w+[\w-\.]*\@\w+((-\w+)|(\w*))\.[a-z]{2,3}$/i }} control={control}
                />
                {errors.email && <span>Email is required</span>}
            </div>
            <div style={{ width: '30%' }}>
                <Controller as={<TextField
                    label="Phone"
                    id="phone"
                    name="phone"
                    type="text"
                    value={phone}
                    placeholder="eg.15556667890"
                    onChange={(e: React.FormEvent<EventTarget>) => {
                        let target = e.target as HTMLInputElement;
                        setPhone(target.value);
                    }}
                    inputProps={{
                        'data-testid': 'phone'
                    }}
                />} name="phone" rules={{ pattern: /\d{11}/ }} control={control}
                />
            </div>
            <div style={{ width: '30%' }}>
                <Controller as={<TextField
                    label="Comments"
                    id="comments"
                    name="comments"
                    type="text"
                    value={comments}
                    placeholder="Comments"
                    rows={6}
                    multiline
                    onChange={(e: React.FormEvent<EventTarget>) => {
                        let target = e.target as HTMLInputElement;
                        setComments(target.value);
                    }}
                    inputProps={{
                        'data-testid': 'comments'
                    }}
                />} name="comments" control={control}
                />
            </div>
        </div>
        <Button
            type="submit"
            aria-label="submit getting-started-form"
            variant="contained"
            color="primary"
            data-testid="getting-started-form-submit-button"
        >
            Submit
        </Button>
    </form>

All fields are validated on submission. Is there anyway to get react-hook-forms to do some kind of validation BEFORE the form is submitted? I would want flags like Angular has for dirty, pristine, etc.

4 Answers

To validate before submit you can use Controller component, inside you use rules prop, like this:

<Controller
      name="name"
      control={control}
      defaultValue=""
      rules={{
          required: getRequired(t),
          validate: getValidation(t)          // <== Here you use validate
      }}
      render={({ onChange, onBlur, value }) => (
           <TextField
               error={Boolean(errors?.name)}
               helperText={errors?.name?.message}
               ...
            />
         )}
       />

Check official documentation example for Controller

official doc example

You can set useForm({mode: "onChange"}) to trigger real time validation ONLY when the input value changes.

I haven’t used react-hook-forms, but I’ve used onblur event handlers to validate individual fields prior to submission.

Related