I do not recognize pattern in HTML5 input


I have a problem in a form where I collect data with input and I want it to only collect digits instead of letters. I am using an IndexedDb database and I keep it in the same as null because of the type of object store that I have created. In the input I'm using pattern to specify that it's only numeric but it does not work for me.


<form name="f1">
    <div class="field">
        <label for="name">NºHistoria</label>
        <input type="text" id="dni1" placeholder="dni" required/>
    <div class="field half">
        <label for="email">Enter MD</label>
        <input type="text" id="md" placeholder="MD" pattern="[0-9]{0,}"required/><br>
<a href class="button submit" onclick="addprueba(dni1);">Save</a>


function addprueba() {
    var active2 = dataBase.result; //conector con la base de datos
    var data1 = active2.transaction(["pacientes"], "readwrite"); //array ,modo de transacción
    var objectDb = data1.objectStore("pacientes");
    var index1 = objectDb.index("by_dni");
    var request1 = index1.get(calcMD5(document.querySelector("#dni1").value));//index1.get(calcMD5(document.querySelector("#dni1").value));//md5(document.querySelector("#dni1").value);//

    request1.onsuccess = function () {

        md1 = parseFloat(document.querySelector("#md").value);
        slv1 = parseFloat(document.querySelector("#slv").value);
        var result = request1.result;
        tipo1 = result.tipo;
        if( md1 >16.33 && tipo1 == "O" )//octopus
            //alert('estoy aquí');
            slv1 = slv1 + ((md1-16.33)/0.84);
        }else if( md1 <-17.35 && tipo1 =="H"){ //humfrey
            slv1 = slv1 + ((md1+17.35)/0.84)

        var active = dataBase.result; //conector con la base de datos
        var data = active.transaction(["pruebas"], "readwrite"); //array ,modo de transacción
        var objectDb1 = data.objectStore("pruebas");
        var index = objectDb1.index("by_dni");
        var request = index.get(calcMD5(document.querySelector("#dni1").value));//
        //aquí le pasaría el dni recogido en la otra página y le añadiría
        var request = objectDb1.put({
            md: document.querySelector("#md").value,
            slv: slv1,
            mes: document.querySelector("#mes").value,
            anyo: document.querySelector("#anyo").value,
            orde: parseFloat(( parseFloat(document.querySelector("#mes").value))+(12* parseFloat((document.querySelector("#anyo").value)-2000))), dni:calcMD5(document.querySelector("#dni1").value)//calcMD5(document.querySelector("#dni1").value)
        request.onerror = function (e) {
            alert(request.error.name + '\n\n' + request.error.message);

        data.oncomplete = function (e) {

            document.querySelector('#md').value = '';
            document.querySelector('#slv').value = '';
            document.querySelector('#mes').value = '';
            document.querySelector('#anyo').value = '';
            alert('The medical test has been created correctly');
asked by Aaron VC 22.06.2016 в 20:24

3 answers


Change property type in input , I'll leave the code

<input type="number" id="dni1" placeholder="dni" required/>

With this change in property type the input should only recognize integers.

answered by 22.06.2016 в 20:35

As you are told if you want to use only numbers it would be better to use the

<input type="number" />

However, if you have to use the pattern in an input text, you can use the regular expression: \d*

<input type="text" pattern="\d*" />

\d is the regular expression for numbers, * means it accepts more than one number.

If you want to restrict the number of numbers entered you could use the attribute maxlength


If you want to accept integers and decimals you can use the following pattern:

function validarNumero(){
  var numero = $("#demo").val();
  if (!numero.match(/^(\d+)(\.\d+)?$/)) {
    alert("Incorrecto no es un decimal");
  } else {
    alert("Correcto es un decimal");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form >
<input id="demo" type="text" pattern="\d+(\.\d+)?" required=""/>
<input type="submit" value="validar html"/>
<button onclick="validarNumero()">Validar JS</button>
answered by 22.06.2016 в 21:02

I think it would be more useful not to allow in real time letters to be entered. For example, to avoid entering letters or more than 8 characters (Peruvian DNI):

function validarDni(e) {
	if(e.value === '') { return; }
	var lastchar = e.value.substring(e.value.length - 1);
    if(isNaN(lastchar) || e.value.length > 8) {
  	    e.value = e.value.substring(0, e.value.length - 1);
input {
  border: 1px solid #ddd;
  color: #777;
  padding: .45rem .55rem;
  transition: border-color .18s ease;
input:focus {
  border-color: rgba(0, 187, 255, .5);
  outline: none;
<input type="text" id="dni" onkeyup="validarDni(this)" onkeydown="validarDni(this)" />

Update per order

If you want decimals, although you can add code to the existing function to make it work, I think it's simpler if you use pattern (regular expressions):

<input type="text" pattern="[-+]?[0-9]*[.,]?[0-9]+" required />

If you want something more dynamic, for example to report that the value that is being entered is incorrect or correct (in real time), you can take advantage of the validation API:

function validateControl(e) {
  if(!e.checkValidity()) {
    if(e.classList.contains('valid')) {
  } else {
    if(e.classList.contains('invalid')) {

function prueba(dni) {
   if(!document.querySelector('form').checkValidity()) {
      alert('El formulario tiene errores');
input {
  border: 1px solid #ddd;
  border-radius: 2px;
  padding: .5rem;
  transition: all .25s ease;
button {
  background-color: #3498db;
  border: 1px solid #3498db;
  border-radius: 2px;
  color: rgba(255,255,255,.9);
  font-family: 'segoe ui';
  padding: .46rem .75rem;
  transition: all .18s ease;
button:hover {
  background-color: #2980b9;
  border-color: #2980b9;
button:focus {
  outline: none;
input:focus {
  border-color: rgb(0,187,255);
  box-shadow: 0 0 3px rgba(0,187,255,.5);
  outline: none;
.valid {
  border-color: #27ae60 !important;
  box-shadow: 0 0 3px rgba(39,174,96,.4) !important;
.invalid {
  border-color: #e74c3c !important;
  box-shadow: 0 0 3px rgba(231,76,60,.4) !important;
  <input type="text" id="dni" onkeyup="validateControl(this)" pattern="[-+]?[0-9]*[.,]?[0-9]+" required title="Ingrese solo números" />
  <button type="submit" onclick="prueba(dni)">Registrar</button>

You could also show a popup showing the error in more detail, etc.

answered by 22.06.2016 в 21:44