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

243
Views
Javascript: solo permita 7 dígitos para la entrada y agregue automáticamente un guión (-) después del tercer número

Quiero restringir el campo de entrada de la siguiente manera.

  • siempre formato 000-0000
  • inserte automáticamente "-" justo después de tener 3 dígitos no permita que el usuario agregue -
  • no permita que un usuario escriba más de 7 dígitos
  • no acepte otro que no sea entero

lo que he probado

En el evento keyup del campo de entrada, estoy llamando al método keyUpValidation

 keyUpValidation(event) { let value = event.target.value; document.getElementById('input').value = value.replace(/[^0-9]/g, "").replace(/(\..*?)\..*/g, "$1"); if (value.length == 3) { document.getElementById('input').value = value + "-"; } },

¿Qué hace este código?

No permite que el usuario agregue nada más que un dígito/número, también inserta un guión (-) después del tercer dígito, pero tan pronto como el usuario ingresa el cuarto dígito, el guión (-) se reemplaza.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Puede utilizar dos entradas. Tome este ejemplo comentado (actualizado para permitir la facilidad de copiar y pegar):

 const wrapper = document.getElementById("wrapper"), p1 = document.getElementById("p1"), dash = document.getElementById("dash"), p2 = document.getElementById("p2"); p1.addEventListener("input", e => { // if length is 3 if (p1.value.length >= 3) { e.preventDefault(); // prevent extra text from being added dash.style.visibility = "visible"; // show dash p2.removeAttribute("disabled"); // remove disabled let remainingValues = p1.value.slice(3); // get next four values p1.value = p1.value.substring(0, 3); p1.setAttribute("disabled", "true"); p2.value = remainingValues.substring(0, 4); // set value for next element; limit to 4; enhance copy-pasting as users will likely copy-paste if (p2.value.length === 4) { p2.setAttribute("disabled", "true"); const userInput = p1.value + p2.value; // done done(userInput); } p2.focus(); // focus } }); p2.addEventListener("input", e => { if (p2.value.length >= 4) { p2.setAttribute("disabled", "true"); // disable to prevent extra text const userInput = p1.value + p2.value; // done done(userInput); } }); wrapper.addEventListener("click", e => { p1.focus(); // emulate input focus }); // uncomment to autofocus: // p1.focus(); function done(val) { console.log(val); }
 /*some styles to make the wrapper look like an input*/ #wrapper { border: 1px solid lightgray; border-radius: 3px; padding: 5px 10px; width: fit-content; transition: .2s; } #wrapper:focus-within { border: 1px solid gray; } #wrapper, #wrapper * { cursor: text; } input[type="number"] { outline: none; border: none; background-color: transparent; -moz-appearance: textfield; } /*remove the step button on numbers*/ input::-webkit-outer-spin-button, input::-webkit-inner-spin-button { -webkit-appearance: none; } #dash { visibility: hidden; } #p1 { width: 25px; } #p2 { width: 30px; }
 <p>Test copy-paste&mdash;copy: 1234567</p> <!--using a wrapper div to emulate an input--> <div id="wrapper"> <input type="number" id="p1" /> <span id="dash">-</span> <input type="number" id="p2" disabled /> </div>

about 4 years ago · Juan Pablo Isaza Report

0

Puede usar la propiedad maxlength en html: Ver Docs

 <input type="number" maxlength="7" />

Use este patrón para separate numbers

 const pattern = new RegExp("(-?[0-9]{3})([0-9]*)");

Aceptar only integer

 const pattern = new RegExp("[^0-9]", "ig");
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!