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>