Validating form in Javascript

Asked

Viewed 179 times

2

I need help validating a form using pure Javascript only.

I cannot make a message error if, for example, the user enters numbers in the username field. The same should happen if the user for example puts an invalid email, type "Aaaaaaaaaa".

I tried to do this in the username, as shown in the code below. If it leaves the field blank or exceeds 16 characters the error works normally. If it fills the message, it disappears, but if it puts numbers and other things the message that was to appear does not appear.

Javascript:

function validar(){
    var usuario = document.getElementById("usuario").value;
    var email = document.getElementById("email").value;
    var senha = document.getElementById("senha").value;
    var confirmarsenha = document.getElementById("confirmar-senha").value;
    var usuario_correto = /^[A-Za-z]+$/;
    var valido = true;

    if(usuario.length < 2 || usuario.length > 16) {
        document.getElementById("msg-usuario").innerHTML="* O nome de usúario precisa ter entre 2 a 16 caracteres";
        valido = false;
    }else if (usuario.match(usuario_correto)) {
        document.getElementById("msg-usuario").innerHTML="* O nome de usúario só pode ter letras [A-Z/a-z]"; 
        valido = false;
    }else{
        document.getElementById("msg-usuario").innerHTML="";
    }

    if(email=="") {
        document.getElementById("msg-email").innerHTML="* O email é obrigatório";
        valido = false;
    }else{
        document.getElementById("msg-email").innerHTML="";
    }
    
    if(senha.length < 5 || senha.length > 16) {
        document.getElementById("msg-senha").innerHTML="* A senha precisa conter de 5 a 16 caracteres";
        valido = false;
    }else{
        document.getElementById("msg-senha").innerHTML="";
    }

    if(confirmarsenha=="") {
        document.getElementById("msg-confirmar-senha").innerHTML="* Confirme a senha";
        valido = false;
    }else{
        document.getElementById("msg-confirmar-senha").innerHTML="";
    }
    
    return valido;
}

Form:

<form class="form-registrar" onsubmit="return validar()">
    <input type="text" placeholder="Nome de usúario" class="form-campo" id="usuario"> 
    <div class="form-msg-erro" id="msg-usuario"></div>

    <br>
    <input type="text" placeholder="Email" class="form-campo" id="email"> 
    <div class="form-msg-erro" id="msg-email"></div>

    <br>
    <input type="text" placeholder="Senha"  class="form-campo" id="senha"> 
    <div class="form-msg-erro" id="msg-senha"></div>

    <br>
    <input type="text" placeholder="Confirmar senha" class="form-campo" id="confirmar-senha"> 
    <div class="form-msg-erro" id="msg-confirmar-senha"></div>

    <br>
    <input type="submit" value="Registrar" class="form-campo-registrar">
</form>
  • If you do this type of validation on several pages of your application, it is worth studying the use of validation libraries, such as Yup, in order to avoid repeating code.

  • For the user name, it could be just if (! usuario.match(/^[A-Za-z]{2,16}$/)) { usuario inválido } (already checks if it has between 2 and 16 letters, and enters if it is not valid)

2 answers

2

Form validation is a validation that occurs in the browser before data is sent to the server.

You enter data and the application checks if the data is correct. If the information is correct, the application allows the data to be sent to the server.

Form validation can be implemented in several different ways and is subdivided into the following categories:

  • Internal form evaluation uses the validation capabilities of HTML5 form.

  • Javascript validation is encoded using Javascript. This validation is completely customizable.

HTML validation

The simplest HTML5 validation feature is the attribute required. To make an entry mandatory, mark the widget with this attribute. When this attribute is set, the form will not be sent and will display an error message when the input is empty. The entry will also be invalid.

Another very common validation feature is the attribute pattern, that expects a Regular Expression as its value. A regular expression (regex) is a standard that can be used to combine character combinations in text strings, so regexs are ideal for form validation and serve a variety of other Javascript uses.

Javascript validation

You should use Javascript if you want to control the appearance of native error messages or handle browsers that do not support HTML internal form validation.

Applies to the following elements::

Properties of the validation API

  • validationMessage : A localized message describing the validation restrictions that the control does not meet (if any) or an empty string if the control is not candidate for validation (willValidate is false).

  • validity : A Validitystate object that describes the element’s validity state.

  • willValidate : Returns true if the element is validated when the form is sent or false otherwise.

Methods of the validation API

  • checkValidity() Returns true if the value of the element has no validation problems, false otherwise.

  • HTMLFormElement.reportValidity() Will return true if the element or its child controls satisfy the validation restrictions. When false é retornado, validation events are fired for each invalid element and validation problems are reported to the user.

  • setCustomValidity() Adds a custom error message to the element.


To force the completion of your form elements I applied the attribute required.

In order for the user to enter a valid name I applied the attribute pattern with the regular expression ^[A-Za-z][A-Z a-z]*$.

In order for the user to enter a valid email I applied the attribute pattern with the regular expression [a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$;

function validar(){
    var usuario = document.getElementById("usuario").value;
    var email = document.getElementById("email").value;
    var senha = document.getElementById("senha").value;
    var confirmarsenha = document.getElementById("confirmar-senha").value;
    
    var valido = true;

    if(usuario.length < 2 || usuario.length > 16) {
        document.getElementById("msg-usuario").innerHTML="* O nome de usúario precisa ter entre 2 a 16 caracteres";
        valido = false;
    }else{
        document.getElementById("msg-usuario").innerHTML="";
    }

    if(email=="") {
        document.getElementById("msg-email").innerHTML="* O email é obrigatório";
        valido = false;
    }else{
        document.getElementById("msg-email").innerHTML="";
    }

    if(senha.length < 5 || senha.length > 16) {
        document.getElementById("msg-senha").innerHTML="* A senha precisa conter de 5 a 16 caracteres";
        valido = false;
    }else{
        document.getElementById("msg-senha").innerHTML="";
    }

    if(confirmarsenha=="") {
        document.getElementById("msg-confirmar-senha").innerHTML="* Confirme a senha";
        valido = false;
    }else{
        document.getElementById("msg-confirmar-senha").innerHTML="";
    }

    return valido;
}
<form class="form-registrar" onsubmit="return validar()">
    <input type="text" placeholder="Nome de usúario" class="form-campo" required id="usuario" pattern="^[A-Za-z][A-Z a-z]*$"> 
    <div class="form-msg-erro" id="msg-usuario"></div>

    <br>
    <input type="email" placeholder="Email" class="form-campo" id="email" required pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$" > 
    <div class="form-msg-erro" id="msg-email"></div>

    <br>
    <input type="password" placeholder="Senha"  class="form-campo" id="senha"> 
    <div class="form-msg-erro" id="msg-senha"></div>

    <br>
    <input type="password" placeholder="Confirmar senha" class="form-campo" id="confirmar-senha"> 
    <div class="form-msg-erro" id="msg-confirmar-senha"></div>

    <br>
    <input type="submit" value="Registrar" class="form-campo-registrar">
</form>

  • 1

    Regarding the use of regex to validate emails, it is worth remembering that it is very difficult to validate 100% of cases. Your regex, for example, considers that .%[email protected] is a valid email (see). I talk more about it here, here, here and here (this last link has other options at the end, just do not recommend the last regex). Anyway, +1 :-)

  • 1

    @hkotsubo, Now that I read it calmly and evaluated link by link I came to the conclusion that I know nothing about Regex and I have updated many systems. Thank you for checking my reply.

  • 1

    The more I study regex, the more I realize that I also know nothing, it seems an endless subject... But I think in the end the best way to check if an email exists is to send a message with a confirmation link, as many services do. It is up to us to evaluate in each case whether it is worth having a more complex regex, or whether a simpler one already solves (assuming that there will be another validation in the backend, for example)

0

Replace your regular expression /^[A-Za-z]+$/ by the expression /[0-9]/

What you want is, if the user enters some number, display an error message stating that in that field can only be entered numbers. So for this we need to check if there are any numbers in the characters typed by the user. In short, you should look for numbers.

In the expression you used, using the match() method, you’re saying that you want the algorithm to look for letters, when in fact what you want to find are numbers.

I’m saying in the regular expression that I used that I’m looking for a number from 0 to 9 anywhere in the string. If he finds his condition

else if (usuario.match(usuario_correto))

will be true and the error message will be displayed as you determined.

In the case of the e-mail field, the HTML itself already brings a resource for e-mail validation. Just in HTML you indicate that the input is email rather than text. This means that you should replace the code snippet

<input type="text" placeholder="Email" class="form-campo" id="email"> 

by code snippet

<input type="email" placeholder="Email" class="form-campo" id="email"> 

Browser other questions tagged

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