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

367
Views
¿Cómo agregar una restricción (que no está implementada) a un formulario?

En algunos navegadores, las entradas como date , time , datetime-local , number no están implementadas y se consideran entradas de texto.

Hice estos RegExp para verificar estos valores de entrada:

 const RegExpYear = '(000[1-9]|00[1-9]\\d|0[1-9]\\d\\d|100\\d|10[1-9]\\d|1[1-9]\\d{2}|[2-9]\\d{3}|[1-9]\\d{4}|1\\d{5}|2[0-6]\\d{4}|27[0-4]\\d{3}|275[0-6]\\d{2}|2757[0-5]\\d|275760)', RegExpMonth ='(0[1-9]|1[012])', RegExpDay = '(0[1-9]|[12]\\d|3[01])', RegExpHour = '(0\\d|1\\d|2[0-4])', RegExpMinSec = '(0\\d|[1-5]\\d)', RegExpMilli = '(00\\d|0[1-9]\\d|[1-9]\\d{2})', patternWeek = new RegExp('^'+RegExpYear+'-W(([1-4][0-9])|(5[0-3])|0[1-9])$'), patternMonth = new RegExp('^'+RegExpYear + '-' + RegExpMonth + '$'), patternDateTimeLocal = new RegExp('^' + RegExpYear + '-' + RegExpMonth + '-' + RegExpDay + 'T' + RegExpHour + ':' + RegExpMinSec + '(?::' + RegExpMinSec + ')?(?:\.' + RegExpMilli + ')?$'), patternDate = new RegExp('^' + RegExpYear + '-' + RegExpMonth + '-' + RegExpDay + '$'), patternTime = new RegExp('^' + RegExpHour + ':' + RegExpMinSec + '(?::' + RegExpMinSec + ')?(?:\.' + RegExpMilli + ')?$'), patternNumber = new RegExp('^-?\d+\.?(\d+)?([eE][+-]?\d+)?$'); document.querySelectorAll('[type=datetime-local], [type=date], [type=time], [type=month], [type=week], [type=number]').forEach(function(a){ let type = a.type, attrtype = a.attributes.getNamedItem('type').value, pattern; if (type !== attrtype) { switch(attrtype) { case 'number' : pattern = patternNumber; break; case 'week' : pattern = patternWeek; break; case 'month' : pattern = patternMonth; break; case 'datetime-local' : pattern = patternDateTimeLocal; break; case 'date' : pattern = patternDate; break; case 'time' : pattern = patternTime; break; } a.addEventListener('input',function(e){ let test = pattern.test(this.value); if (test) { a.classList.add('valid') a.classList.remove('invalid') } else { a.classList.add('invalid') a.classList.remove('valid') } }); } });

De esta manera, puedo diseñar las entradas incorrectas pero no puedo evitar el envío del formulario.

¿Es posible agregar una restricción que pase a través de la propiedad ValidityState ?

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

0

No tendrá que volver a validar todas las entradas o evitar el envío de formularios dentro del controlador de eventos onsubmit , si usa la API de validación de restricciones DOM incorporada. Cada elemento de entrada se valida a sí mismo e informa al formulario si es válido o no. Se puede realizar un manejo especial dentro del controlador de eventos onInput.
Manifestación:

 const fruitRegx = "(?!\s*[Mm]ango).*" // we don't want mango // set patterns on all required input elements let inpt = document.getElementById('choose'); inpt.setAttribute("pattern", fruitRegx); // set input handlers inpt.addEventListener('input', function(e) { if (inpt.validity.patternMismatch) { inpt.setCustomValidity("I said no mango!!"); // if pattern doesn't mismatch report it // rest is taken care of automatically inpt.reportValidity(); } else { inpt.setCustomValidity(""); } }); // this one has no pattern assigned, so doing validation manually choose2.addEventListener('input', function(e) { let val = e.target.value; if (val.includes("banana")) { e.target.setCustomValidity("How dare you!!"); e.target.reportValidity(); } else { e.target.setCustomValidity(""); } }); function send(event) { // mimicking form submit output.innerHTML += `Requesting ${choose.value} and ${choose2.value}...<br>`; // just for the demo preventing form submission event.preventDefault(); return false; }
 input:invalid { background-color: rgb(255, 196, 196); } input:valid { background-color: lightgreen; }
 <form onsubmit="send(event)" target="_self"> <label for="choose">What fruit would you prefer? Except mango!</label><br> <input id="choose" required><br><br> <label for="choose">This one doesn't have pattern validation. But don't enter 'banana'!</label><br> <input id="choose2" required><br><br> <button>Submit</button> <pre id=output></pre> </form>

Si escribe 'mango' en la demostración anterior, no se llama al método de send .
También tenga en cuenta cómo <input> obtiene automáticamente las pseudoclases CSS :valid e :invalid . Así que el estilo se cuida automáticamente.

Si está buscando una solución para evitar el envío de formularios, la demostración anterior ya lo está haciendo. Para obtener más información, consulte https://stackoverflow.com/a/8664680/15273968

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!