Home > Net >  React Native - React Hook Forms Validation
React Native - React Hook Forms Validation

Time:11-24

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;

CodePudding user response:

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

{errors.senha && <Text>{errors.senha.message}</Text>}
  • Related