How to validate form fields using pure Javascript

Asked

Viewed 891 times

1

I’m trying to use a validation in a form I have using Javascript, but it’s not working very well, what I’m trying to do is this:

I defined a div like this:

<style type="text/css">
    .msg-erro{ color: red; }
</style>

In my input I put a <span> thus:

<div class="col-md-12 col-sm-12">
   <label>Empresa *</label>
   <input type="text" id="Empresa" name="Empresa" value="" class="form-control required">
   <span class='msg-erro msg-empresa'></span>
</div>

And at the time of recording the record is like this:

// RECUPERA VARIÁVEL DO CAMPO HIDDEN
var IdCandidato = $("#pk").val();
// RESGATANDO VALORES 
var Empresa = $("#Empresa").val();
var Cargo = $("#Cargo").val();
var DataEntrada = $("#DataEntrada").val();
var DataSaida = $("#DataSaida").val();
var UltimoSalario = $("#UltimoSalario").val();
var Atividades = $("#Atividades").val();
var contErro = 0;

/* Validação do campo nome */
MsgEmpresa = document.querySelector('.msg-empresa');
if (Empresa.value == ""){
    MsgEmpresa.innerHTML = "Favor preencher a Empresa";
    MsgEmpresa.style.display = 'block';
    contErro += 1;
} else {
    MsgEmpresa.style.display = 'none';
}   

if(contErro > 0){
    evt.preventDefault();
}   

But the message is not being displayed and the form is submitted.

The layout of the form looks like this:

inserir a descrição da imagem aqui

  • Your feedback is very important for people who want to help!. That’s why it’s important to mark the response that helped you in your project.

  • Hello @Cristianogilbertojoão, thanks for the tip, but none of the answers helped me in what I need, even giving me a good direction.

3 answers

1

To do this validation with jQuery I do it like this: In HTML I create a tag with the error message, put None display by the same jquery and valid when submitting the form, in a variable I put value false to start and if it enters some validation that is wrong it turns true, and only register if it is false, follows below an example.

HTML:

<input id="exemplo" name="exemplo">
<span class='msg-de-erro'>Selecione o campo</span>

jQuery:

var focus = false;
$('.msg-de-erro').css({'display': 'none'});

 $('#btn_enviar').click(function () {
        var envioAjax = false;
        //Validar campos do formulário
        if ('' == $('#exemplo').val()) {
            $('#exemplo').css({'border-color': 'red'});
            $('#exemplo').parent().find('.msg-de-erro').css({'display': 'block'});
            if (!focus) {
                jQuery('#exemplo').focus();
                focus = true;
            }
        } else {
            $('#exemplo').css({'border': '1px solid #ced4da'});
            $('#exemplo').parent().find('.msg-de-erro').css({'display': 'none'});
            focus = false;
        }
        if (!focus) {
            var exemplo = $('#exemplo').val();

            $.ajax({
                type: 'POST',
                url: url,
                data: exemplo,
                success: function (data) {                        
                },
                error: function (data) {
                    console.log('não cadastrou ');
                }
            })
        }
    });

To complement for example gave the error message but if the user is typing again the error message does not disappear then I do the following.

jQuery

$('#exemplo').change(function () {
    $('#exemplo').css({'border': '1px solid #ced4da'});
    $('#exemplo').parent().find('.msg-de-erro').css({'display': 'none'});
});

1


Usually when developing a System it is convenient to create a generic form validation function.

I tried to create something based on jQuery and underscorejs I might be able to help you:

var passwordValidate = function() {
  let passwordAgain = $('input[type="password"]#passwordAgain').val(),
    password = $('input[type=password]#password').val();

  if ($('input[type=password]#password').attr('data-noHandle') === 'true') {
    return true
  }

  if (password === passwordAgain) {
    return true;
  }

  return false;
};

var submitFormValidate = function(event) {
  var getHtmlError = (msg) => `<span class="wrap-center input-error-span ">${msg}</span>`;
  var notRemoveElemInDOM = ['textarea', 'select', 'input'];
  //Validate email function
  var validateEmail = (email) => {
    var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(email);
  }

  if (event.type === "submit") {
    //input element
    var elem = $('form textarea[required],form select[required], form input[required]').not('.hidden').not(':hidden').filter(function() {

      if (this.type === 'number') {

        var validaLength = $(this).attr('length'),
          minLength = $(this).attr('min-length'),
          maxLength = $(this).attr('max-length'),
          length = this.value.length;

        if (typeof validaLength !== 'undefined') {
          return length !== parseInt(validaLength);
        } else {

          if ((typeof minLength !== 'undefined') && (typeof maxLength === 'undefined')) {
            return length < parseInt(minLength);
          }

          if ((typeof maxLength !== 'undefined') && (typeof minLength === 'undefined')) {
            return length > parseInt(maxLength);
          }

          if ((typeof maxLength !== 'undefined') && (typeof minLength !== 'undefined')) {
            if (length < minLength) {
              return true;
            } else if (length > maxLength) {
              return true;
            } else {
              return false;
            }
          }

          if ((typeof maxLength === 'undefined') && (typeof minLength === 'undefined')) {
            return this.value == "";
          }
        }
      } else if (this.type === 'email') {
        if (this.value !== "") {
          return !validateEmail($(this).val());
        } else {
          return this.value == "";
        }

      } else if (this.type === 'select-one') {
        if ($(this).val() === null) {
          return true;
        } else {
          return $(this).val() === "";
        }

      }  {
        return this.value == "";
      }

    })[0];

    if ((typeof elem !== 'undefined') && !elem.hidden) {

      //Focus
      if ($(elem).attr('trueType') !== 'date') {
        $(elem).focus();
      }

      elem.scrollIntoView(false);


      //placeholder messages
      var messageValidat = $(elem).attr('messageValidat'),
        oldPlaceholder = $(elem).attr('placeholder');
      var html = getHtmlError(messageValidat || 'Este campo e obrigatorio');
      //DATE

      //SELECT-ONE
      if (elem.type === "select-one" && !elem.hidden) {
        $(html).insertAfter(elem);
        $(elem).addClass('input-error');
      } else
        //Campos vazios
        if ((elem.value === '') && (!$(elem).hasClass('input-error'))) {

          $(elem).attr('placeholder', messageValidat);
          $(elem).addClass('input-error');
          $(html).insertAfter(elem);

        } else
          //Campos nao vazios
          if (elem.value !== '') {
            //Campos de tipo 'email'
            if (elem.type === 'email') {
              if (!validateEmail(elem.value)) {
                $(html).insertAfter(elem);
                $(elem).addClass('input-error');
              } else {
                $(elem).removeClass('input-error');
                if (!(_.contains(notRemoveElemInDOM, $(elem).next().prop("tagName").toLowerCase()))) {
                  $(elem).next().remove();
                }
              }

            }

            //Campos de tipo 'number'
            if (elem.type === 'number') {
              var validaLength = parseInt($(elem).attr('length')),
                length = elem.value.length;

              if (validaLength) {
                if (validaLength !== length) {
                  $(html).insertAfter(elem);
                  $(elem).addClass('input-error');
                } else {
                  $(elem).removeClass('input-error');

                  if (!(_.contains(notRemoveElemInDOM, $(elem).next().prop("tagName").toLowerCase()))) {
                    $(elem).next().remove();
                  }
                }
              } else {
                $(html).insertAfter(elem);
                $(elem).addClass('input-error');
              }

            }


          }


      //OTHER
      $(elem).on('keydown', function(e) {
        if ($(elem).hasClass('input-error')) {

          var tagName = $(elem).next().prop("tagName");
          if (tagName) {
            if (!(_.contains(notRemoveElemInDOM, tagName.toLowerCase()))) {
              $(elem).next().remove();
            }
          } else {
            $(elem).next().remove();
          }

          $(elem).attr('placeholder', oldPlaceholder);
          $(elem).removeClass('input-error');
        }
      });

      //SELECT-ONE
      $(elem).on('change', function(e) {
        if ($(elem).hasClass('input-error')) {
          $(elem).removeClass('input-error');
        }
      });

      //Date
      $(elem).on('focus', function(e) {
        if ($(elem).hasClass('input-error')) {

          if (!(_.contains(notRemoveElemInDOM, $(elem).next().prop("tagName").toLowerCase()))) {
            $(elem).next().remove();
          }

          $(elem).removeClass('input-error');
        }
      });

      return false;
    }

  }

  return passwordValidate();
};



window.onload = () => {
  document.getElementById("registoUtilizador").addEventListener("submit", myFunction);

  function myFunction(event) {
    event.preventDefault();
    // Validar o form
    if (submitFormValidate(event)) {
      alert('Validou com sucesso')
    }
  }
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script src="https://underscorejs.org/underscore.js"></script>

<form class="" id="registoUtilizador" novalidate="novalidate" method="post" style="">
  <div id="primeiroNome">
    <input type="text" messagevalidat="Primeiro nome obrigatório" id="primeiroNome" name="primeiroNome" placeholder="Primeiro Nome" required="">
  </div>
  <div class="">
    <input type="email" id="email" messagevalidat="E-mail obrigatório" name="email" value="" placeholder="E-mail" required="">
  </div>
  <div>
    <input type="number" id="cel" min-length="8" max-length="9" messagevalidat="número do celular obrigatório" name="cel" value="" placeholder="Celular">
  </div>
  <div>
    <select id="genre" name="genre" required="required">
      <option disabled="" selected="">Sexo</option>
      <option value="M">Masculino</option>
      <option value="F">Feminino</option>
    </select>
  </div>
  <div>
    <input type="password" name="password" id="password" value="" placeholder="Palavra-Passe" required="">
  </div>
  <div>
    <input type="password" name="passwordAgain" passwordagain="passwordAgain" id="passwordAgain" value="" placeholder="Confirmar Palavra-passe" required="">
  </div>
  <div>
    <button id="button" type="submit" class="">
      Enviar
    </button>
  </div>
</form>

  • The composition of HTML:

The requered attribute indicates the inputs that will be validated.

messagevalidat: Error message;

min-length: Minimum number of characters;

max-length: Maximum number of characters;

length: Number of characters;

The rest is a matter of css.

0

No need for JS to do form validation, a good HTML and CSS is enough

I’ll leave just one example for base use

body, form {
  width: 100vw;
  height: 100vh;
  margin: 0;
}
form {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

input {
  margin-top: 16px;
  border: none;
  border-bottom: 1px solid black;
}
input:invalid {
  border-bottom-color: red;
}
input + .error {
  display: block;
  visibility: hidden;
  opacity: 0;
  position: relative;
  height: 14px;
  font-size: 14px;
  color: red;
  transition: opacity 1s linear;
}
input:invalid + .error {
  visibility: visible;
  opacity: 1;
}
<form>
  <div>
    <input type="text" placeholder="Nome" minlength="5" maxlength="50" patter="^[a-zA-Z]+(([',. -][a-zA-Z ])?[a-zA-Z]*)*$" required>
    <span class="error">Entre 5 e 50 caracteres</span>
  </div>

  <div>
    <input type="email" placeholder="Email" required>
    <span class="error">Email inválido</span>
  </div>
</form>

I put a div by organization only, to encapsulate the field and the error text. Being the text showing when the input contains some error. You can use the validation attributes (minlength, maxlength, required, pattern among others), but note that only by setting the type of input already has a validation, as in the example, the type email

Browser other questions tagged

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