Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

152
Views
¿Cómo validar el número de teléfono onClick en React?

Quiero validar el número de teléfono al hacer clic en un botón. Esto es lo que he hecho, soy nuevo en ReactJS. Por favor, ayúdame en esto. Cuando hago clic en enviar ese tiempo, mostrará un mensaje de error.

 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 answers
Answer question

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 Report

0

Parece que entiende la construcción básica de un componente de función usando el estado, pero hay un par de problemas.

  1. Todos los controladores de eventos recibirán ese evento como argumento. Entonces puede escribir <input onChange ={onChangeValidate} /> y <button onClick={validateFunc}>Submit</button> .

  2. Tal vez sea mejor usar la test en lugar de la match en este caso: /[0-9]{10}/.test(phone) .

Pero también creo que debería permitir que el formulario haga la validación por usted, en lugar de JS. De esta manera, no necesita el estado de error ya que la validación se maneja automáticamente.

Envuelva su entrada y botón en un elemento <form> con su propio controlador onSubmit , haga que la entrada required y agregue type="submit" al botón. Puede usar CSS para cambiar el estilo de la entrada si no es válido.

 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 Report

0

¡Prueba esto!

 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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!