I am trying to validate the strings of several inputs with jQuery taking their pattern attributes, this with the purpose of if the values are valid, change styles and allow the form to be submitted.
As an example if we put "Carlos" it should be valid and if we enter "Carlos." It should be invalid, however when doing the test it always gives me the alert("valid").
It seems to me that everything is correct but someone give me a hand to find the error
<div class="wrapInput">
<label for="example">Usuario</label>
<div class="inputItem">
<input type="text" name="example" minlength="10" maxlength="30" pattern="[a-zA-ZàáâäãåąčćęèéêëėįìíîïłńòóôöõøùúûüųūÿýżźñçčšžÀÁÂÄÃÅĄĆČĖĘÈÉÊËÌÍÎÏĮŁŃÒÓÔÖÕØÙÚÛÜŲŪŸÝŻŹÑßÇŒÆČŠŽ∂ð0-9 ,'-]+" required />
<i class="icon-contact"></i>
</div>
</div>
$('.inputItem').on('focusout', 'input',function() {
var typeValue = $(this).attr('type');
var boxContainer = $(this).closest('div.wrapInput');
var inputValue = $(this).val();
var patternInput = new RegExp( $(this).attr('pattern') );
if(inputValue != ''){
if(!inputValue.match(patternInput)){
alert('invalid');
boxContainer.removeClass('inputValid');
boxContainer.addClass('inputInvalid');
} else {
alert('valid');
boxContainer.removeClass('inputInvalid');
boxContainer.addClass('inputValid');
sendValid = true;
}
}
});
Your problem is that you're saying, "if the string contains one or more characters inside the brackets" it's valid, so the result of your regular expression will validate a lot of strings and many you don't want to be validated (like is happening to you).
You should modify your regular expression to:
I've just added a
^
to the beginning, it translates as "it has to start with".And at the end of the regular expression a
$
that translates to "string ends with".