Disable button in React via validation

Asked

Viewed 40 times

-1

Hey, good night, fellas, what’s up? I’m having trouble with the validation of a button, it should be disabled if the validation did not pass, but as I am a student yet, I can’t tell for sure where I am wrong, because the validation does not work, someone could give me a light please?

import React, { useState } from 'react';
import { Redirect } from 'react-router-dom';

function Login() {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const minPwdLength = 6;
  const handleSubmit = (e) => {
    e.preventDefault();
    setIsLoggedIn(true);
  };
  if (isLoggedIn) return <Redirect to="/carteira" />;
  return (
    <form onSubmit={ handleSubmit }>
      <label htmlFor="email">
        Email:
        <input
          type="email"
          name="email"
          id="email"
          placeholder="Digite o seu email"
          data-testid="email-input"
          value={ email }
          onChange={ (e) => setEmail(e.target.value) }
        />
      </label>
      <label htmlFor="password">
        Senha:
        <input
          type="password"
          name="password"
          id="password "
          placeholder="Digite a sua senha"
          data-testid="password-input"
          value={ password }
          onChange={ (e) => setPassword(e.target.value) }
        />
      </label>
      <button
        type="submit"
        disabled={
          !email.match(
            /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/,
          ) && !password.length >= minPwdLength
        }
      >
        Entrar
      </button>
    </form>
  );
}

export default Login;

1 answer

1


Hello, I made a small change to your code.

I added the regex email before the function

Follow the code of the regex

let REGEX_EMAIL = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

And in the disabled of only if button I did the following validation

Follow the validation code

disabled={!REGEX_EMAIL.test(email) || password.length <= minPwdLength}

In this disable code it does the email test on regex and returns true or false and the password is similar to your.

I hope I’ve helped

Browser other questions tagged

You are not signed in. Login or sign up in order to post.