Validate input with jQuery and regular expressions

2

I am working with ASP.NET MVC5, and trying to validate an input with jQuery and regular expressions. What I'm trying to do is input only letters including 'ñ' and vowels with tilde.

Code:

$('#RazonSocial').on('keypress', function (e) {
    if (!/^[a-zA-ZáéíóúüñÁÉÍÓÚÜÑ]*$/.test(e.target.value)) {
        e.preventDefault();
    }
});

The problem with this code is that when I enter digits and press a space, it no longer allows to enter more digits; and when I press a number it shows me the first number that I typed.

    
asked by Pedro Ávila 20.01.2017 в 04:16
source

1 answer

1

When you try to validate in the event keypress , it is not validated:

  • When text is pasted

  • In many mobile browsers

Even preventing the entry of certain characters used to be something of the past. Nowadays, you can usually enter any character and validate in the event blur , or at the time of sending the form.

But following your idea, we could validate in the event input . This code removes all that character that is not alphanumeric or space:

$('#RazonSocial').on('input', function (e) {
    if (!/^[ a-z0-9áéíóúüñ]*$/i.test(this.value)) {
        this.value = this.value.replace(/[^ a-z0-9áéíóúüñ]+/ig,"");
    }
});
<!-- jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<!-- HTML -->
<input type="text" id="RazonSocial">


Alternatively, we could use jQuery Validation Plugin .

$(function() {
  
    $.validator.addMethod("alfanumOespacio", function(value, element) {
        return /^[ a-z0-9áéíóúüñ]*$/i.test(value);
    }, "Ingrese sólo letras, números o espacios.");
    
    $('#formulario').validate({
        rules: {
            RazonSocial: {
                alfanumOespacio: true,
                required: true,
            }
        }
    });
  
  
    //Para probar qué haría en el envío del form
    $('#probar').on('click', function(){
        console.log('Válido:',$('#formulario').valid());
    });
  
    
});
<!-- jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- jQuery Validation Plugin -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.15.0/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.15.0/additional-methods.min.js"></script>

<!-- HTML -->
<form id="formulario">
    <div>
        <input type="text" name="RazonSocial">
    </div>
    <div>
        <input type="button" id="probar" value="Probar">
    </div>
</form>
    
answered by 20.01.2017 в 06:04