Validate name field - Jquery

Asked

Viewed 2,168 times

4

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

  • Letters (Upper and Lower Case)
  • Numbers
  • Spaces
  • Maximum 30 characters
  • There can be no double space
  • There cannot be space at the beginning and at the end (As at the End the over name will have to have space, then it will not be necessary, because I will validate with Trim subsequently)

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 );
});

3 answers

1


Us inputs use the maxlength attribute with a value of 30

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

to remove double spaces in the 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>

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

Another option on 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>

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

1

Regular expression

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

Meaning

  • ^ - Circumflex that matches the beginning of the string.
  • [a-z\d] - List a letter or number (not to allow spaces at the beginning).
  • (?:[a-z\d]| (?! |$)){0,29} - This is a group which is repeated between 0 and 29 times, marrying 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 Lookahead negative).
  • $ - End of the chain.
  • /i - upper and lower case.

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 -->
<input type="text" id="nome_p" name="nome_p">



HTML5 Pattern attribute (no Javascript)

In HTML5 you can use the attribute Pattern of an <input element> (See the compatibility).

<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>

-1

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

I believe 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>


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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.