2

I'm building a simple register form usin react-hook-form following the documentation and I'm not really sure about how to use yup and validations

First, I had defined object with some rules, but then when I added Controller component I have a prop called rules. Controller errors are working, but not the ones from yup schema.

Is yup necessary? Can someone explain too me a little better the proper way to use it? Also, I'm not really sure about how to define rules at Controller component

import React, { useEffect } from "react";
import {
  View,
  TextInput,
  TouchableOpacity,
  Text,
  StyleSheet,
} from "react-native";
import { useForm, Controller } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import * as yup from "yup";

const schema = yup.object({
  email: yup.string().email().required("E-mail não informado"),
  senha: yup
    .string()
    //.required("Senha não informada")
    .min(8, "Senha muito pequena - deve ter no mínimo 8 caracteres"),
});

const AcessoFormulario = ({ tipoUsuario }) => {
  const {
    control,
    register,
    setValue,
    handleSubmit,
    formState: { errors },
  } = useForm({
    resolver: yupResolver(schema),
    defaultValues: {
      email: "",
      senha: "",
      confirmacaoSenha: "",
    },
  });

  useEffect(() => {
    register("email");
    register("senha");
    register("confirmacaoSenha");
  }, [register]);

  const enviar = (dados) => {
    console.log(data);
    //TODO firebase auth
  };

  return (
    <View style={styles.container}>
      <View style={styles.subContainer}>
        <Text style={styles.label}>E-mail:</Text>
        <Controller
          control={control}
          rules={{
            required: true,
          }}
          render={({ field: { onChange, onBlur, value } }) => (
            <TextInput
              style={styles.input}
              onBlur={onBlur}
              onChangeText={onChange}
              value={value}
            />
          )}
          name="Email"
        />
        {errors.email && <Text>Obrigatório....</Text>}
      </View>
      <View style={styles.subContainer}>
        <Text style={styles.label}>Senha:</Text>
        <Controller
          control={control}
          rules={{
            maxLength: 100,
          }}
          render={({ field: { onChange, onBlur, value } }) => (
            <TextInput
              style={styles.input}
              onChangeText={(text) => setValue("senha", text)}
            />
          )}
          name="senha"
        />
        {errors.senha && <Text>Obrigatório....</Text>}
      </View>
      <View style={styles.subContainer}>
        <Text style={styles.label}>Confirmação de senha:</Text>
        <Controller
          control={control}
          rules={{
            maxLength: 100,
          }}
          render={({ field: { onChange, onBlur, value } }) => (
            <TextInput
              style={styles.input}
              onChangeText={(text) => setValue("confirmacaoSenha", text)}
            />
          )}
          name="confirmacaoSenha"
        />
        {errors.confirmacaoSenha && <Text>Obrigatório....</Text>}
      </View>

      <TouchableOpacity style={styles.btnEnviar} onPress={handleSubmit(enviar)}>
        <Text style={styles.btnTexto}>Registrar-se</Text>
      </TouchableOpacity>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    display: "flex",
    flexDirection: "column",
    marginTop: 40,
    margin: 10,
    padding: 10,
    backgroundColor: "#77d477",
    borderRadius: 20,
  },
  input: {
    borderWidth: 2,
    borderColor: "#ffffff",
    borderRadius: 6,
    margin: 2,
  },
  label: {
    color: "#ffffff",
    fontWeight: "bold",
    fontSize: 15,
  },
  subContainer: {
    margin: 15,
    //padding: 10
  },
  btnEnviar: {
    backgroundColor: "#ffffff",
    margin: 15,
    padding: 10,
  },
  btnTexto: {
    color: "#77d477",
    textAlign: "center",
    fontWeight: "bold",
    fontSize: 20,
  },
});

export default AcessoFormulario;

1 Answer 1

1

You can access it using the message for every property inside errors. For example:

{errors.senha && <Text>{errors.senha.message}</Text>}
Sign up to request clarification or add additional context in comments.

2 Comments

thanks. what is the difference between yup and controller rules?
yup comes in handy with complex validations. However, the above validations can be done easily with react-hook-form controller rules, example: codesandbox.io/s/controller-rules-ipynf. You can find more details in the documentation.

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.