Display message for validation of a form instead of alert

2

I am making a form that if the user leave the field name blank, display the message in the field, rather than an alert. document.write does not work with function through an event. I'm using innerHTML and textContent . However, I can not display the message. I made two codes, let's see:

<html>
<body>
    <script>

        function validar() {

            if (document.formulario.nome.value.length == 0) {
                var alerta = "O nome deve ser informado";
                var aviso.innerHTML = alerta;
            }
        }

    </script>

    <form name="formulario">
        Nome: <input type="text" name="nome">

        <input type="submit" value="Enviar" name="cadastro" onclick="validar()">
    </form>
</body>
</html>

Second code:

<html>
<body>
    <script>
        function validar() {

            if (document.formulario.nome.value.length == 0) {
                var alerta = document.getElementById('alerta');
                alerta.textContent = "O nome deve ser informado";
            }
        }
    </script>

    <form name="formulario">
        Nome: <input type="text" name="nome"> <input type="submit"
            value="Enviar" name="cadastro" onclick="validar()">
    </form>
</body>
</html>
    
asked by anonymous 04.12.2015 / 13:19

1 answer

1

One option is to create a div just after txt or in a location of your own, and in this div you will do innerHTML of the validation message, I gave you an example to see how it works:

document.getElementById("btnEnviar").addEventListener("click", validar, false);

function validar() {
  var $divMensagem = document.getElementById('divMensagem');
  var $txtNome = document.getElementById('txtNome');

  if ($txtNome.value.length == 0)
    $divMensagem.innerHTML = 'O nome deve ser informado';
  else
    $divMensagem.innerHTML = '';
}
Nome:
<input type="text" name="nome" id="txtNome">
<div id="divMensagem"></div>
<input type="submit" value="Enviar" id="btnEnviar" name="cadastro">
    
04.12.2015 / 13:36