Validate field name - Jquery

5

I would like to know how do I validate a field name, to accept:

  
  • Letters (Uppercase and Lowercase)
  •   
  • Numbers
  •   
  • Spaces
  •   
  • Maximum 30 characters
  •   
  • There can be no double space
  •   
  • There can be no space at the beginning and at the end (As in the End the over name will have to have space, then it will not be necessary, as I will validate   with trim later)
  •   

Code

$("[name=nome_p]").keyup(function() {
        var $this = $( this ); //armazeno o ponteiro em uma variavel
        var valor = $this.val().replace(/[^a-z0-9 ]+/gi,'');
        $this.val( valor );
});
    
asked by anonymous 05.04.2017 / 02:08

3 answers

1

In inputs use the maxlength attribute with a value of 30

<input type="text" maxlength="30" name="nome_p" value="" />
  

To remove double spaces in script add

valor = valor.replace(/( )+/g, ' ');

$("[name=nome_p]").keyup(function () { 
    	var $this = $( this ); //armazeno o ponteiro em uma variavel
		    var valor = $this.val().replace(/[^a-z0-9 ]+/gi,'');
		    valor = valor.replace(/( )+/g, ' ');
		    $this.val( valor );
	});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script><inputtype="text" maxlength="30" name="nome_p" value="" />
  

Another option in script add

while (valor.indexOf(' ') != -1) valor = valor.replace(' ', ' ');

    $("[name=nome_p]").keyup(function () { 
    	var $this = $( this ); //armazeno o ponteiro em uma variavel
		    var valor = $this.val().replace(/[^a-z0-9 ]+/gi,'');
		    while (valor.indexOf('  ') != -1) valor = valor.replace('  ', ' ');
		    $this.val( valor );
	});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script><inputtype="text" maxlength="30" name="nome_p" value="" />
    
05.04.2017 / 04:14
1

Regular expression

/^[a-z\d](?:[a-z\d]| (?! |$)){0,29}$/i

Meaning

  • ^ - Circumflex that marries the beginning of the string.
  • [a-z\d] - List that matches a letter or a number (not to allow spaces at the beginning).
  • (?:[a-z\d]| (?! |$)){0,29} - This is a group that is repeated between 0 to 29 times, matching a character of the two alternatives :
    • [a-z\d] - letter or number.
    • (?! |$) - space that is not followed by another space or the end of the string (uses a negative lookahead ).
  • $ - End of string.
  • /i - uppercase and lowercase.

Example

$(function() {
    let er = /^[a-z\d](?:[a-z\d]| (?! |$)){0,29}$/i;
    
    $("#nome_p").on("input", function() {
        if (er.test($(this).val())) {
            // ✔️ válido
            $(this).removeClass("invalido");
        } else {
            // ✖️ inválido
            $(this).addClass("invalido");
        }
    });
});
input.invalido:focus {
    border: 2px dashed red;
    background-image: url(https://i.stack.imgur.com/NAJqp.png);
    background-position: right top;
    background-repeat: no-repeat;
}
<!-- jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><!--HTML--><inputtype="text" id="nome_p" name="nome_p">


HTML5 pattern attribute (without Javascript)

In HTML5 you can use the attribute pattern of an < input > (See the compatibility / a>) .

<input pattern="Expressão regular" title="mensagem de erro">


Code

input[type="text"]:required:invalid,
input[type="text"]:focus:invalid {
    border: 2px dashed red;
    background-image: url(https://i.stack.imgur.com/NAJqp.png);
    background-position: right top;
    background-repeat: no-repeat;
}

input[type="text"]:valid {
    border: 2px solid black;
    background-image: url(https://i.stack.imgur.com/X6zP2.png);
    background-position: right top;
    background-repeat: no-repeat;
}
<form>
    <input type="text"
           placeholder="Nome" 
           pattern="[A-Za-z\d](?:[A-Za-z\d]| (?! |$)){0,29}" 
           title="• Letras&#10;• Números&#10;• Espaços&#10;• Máximo 30 caracteres&#10;• Não pode haver espaço duplo&#10;• Não pode haver espaço no início e no fim" 
           required
           >
    <input type="submit">
</form>
    
07.04.2017 / 08:59
-1

To limit size use the maxlength="30" attribute of the input tag, to remove the spaces at the beginning and end of the string you'd better use a trim function on the server side or wherever you get this data , and to allow only the characters you described it is best to use the keypress function and return false if it does not meet your conditions.

I think something like this might help:

$(document).ready(function() {
  $("[name=nome_p]").keypress(function(e) {
    var char = String.fromCharCode(e.which);
    var value = $(this).val();

    if (!/[a-z0-9 ]+/gi.test(char)) {
      return false;
    }

    if (value.substr(value.length - 1) === ' ') {
      return false;
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script><inputtype="text" name="nome_p" maxlength="30" />
    
05.04.2017 / 03:27