Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

153
Visualizações
How to validate phone number onClick in React?

I want to validate phone number onClick of a button. This is what I have done, I am new to ReactJS. Please help me in this. When I click submit that time it will show an error message.

const [phoneNo, setPhoneNo] = useState(false)
const [errorMessage, setErrorMessage] = useState("")

const validateFunc = () => {
  setPhoneNo(true)
}

const onChangeValidate= (e) => {
   var phone = e.target.value;
   if( !(phone.match('[0-9]{10}')) ){
     setPhoneNo(false);
     setErrorMessage("Please enter 10 digit")
    }else{
    }
    setPhoneNo(true)
   }




----
<input onChange ={() => onChangeValidate(e)} />
<button onClick = {validateFunc()}>Submit</button>
<p>{errorMessage}</p>
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

const onChangeValidate= (e) => {
   var phone = e.target.value;
   if( !(phone.match('[0-9]{10}')) ){
     setPhoneNo(false);
     setErrorMessage("Please enter 10 digit")
    }else{
    setPhoneNo(true)
    }
}
<p>{setPhoneNo===false?errorMessage:''}</p>

Set like these if there will be setphone no false then msg will be shown 
about 4 years ago · Juan Pablo Isaza Relatório

0

You seem to understand the basic construct of a function component using state but there are a couple of issues.

  1. All event handlers will receive that event as an argument. So you can write <input onChange ={onChangeValidate} /> and <button onClick={validateFunc}>Submit</button>.

  2. It maybe better to use test rather than match in this instance: /[0-9]{10}/.test(phone).

But I also think that you should allow the form to do the validation for you, rather than JS. This way you don't need the error state as the validation is all handled automatically.

Wrap your input and button in a <form> element with its own onSubmit handler, make the input required, and add a type="submit" to the button. You can use CSS to change the style of the input if it's not valid.

const { useState } = React;

function Example() {

  const [phoneNo, setPhoneNo] = useState('');

  // Update the phone number state when the
  // input changes
  function handleChange(e) {
    setPhoneNo(e.target.value);
  }

  // In this example prevent the form from
  // submitting so we can log the state, but you'll probably
  // want to do an AJAX call here to submit the form
  function handleSubmit(e) {
    e.preventDefault();
    console.log(phoneNo);
  }

  // Add your regex pattern to the input
  // and make it required. If you submit an invalid
  // number you'll get a neat little tooltip warning
  // you of the issue, and the form won't submit until
  // it has been fixed 
  return (
    <form onSubmit={handleSubmit}>
      <input
        pattern="[0-9]{10}"
        placeholder="Add a phone number"
        onChange={handleChange}
        required
      />
      <button type="submit">Submit</button>
    </form>
  );

}

ReactDOM.render(
  <Example />,
  document.getElementById('react')
);
input:invalid { border: 1px solid red; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>

about 4 years ago · Juan Pablo Isaza Relatório

0

Try this!

const [phoneNo, setPhoneNo] = useState(false)
const [errorMessage, setErrorMessage] = useState("")

const validateFunc = () => {
  if(phoneNo) {
    // perform submittion
  }
}

const onChangeValidate= (e) => {
   var phone = e.target.value;
   if( !(phone.match('[0-9]{10}')) ){
     setPhoneNo(false);
     setErrorMessage("Please enter 10 digit");
    }else{
     setPhoneNo(true);
     setErrorMessage("");
    }
    
   }




----
<input onChange ={(e) => onChangeValidate(e)} />
<button type="button" onClick = {validateFunc()}>Submit</button>
<p>{errorMessage}</p>
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda