Custom validation error Html and Javascript

0

Good afternoon, I've been studying about 2 weeks web programming and javascript. This time I'm trying to validate my form in php, but whenever I send it, it does not show the validation errors and the default validation of html appears.

This is my Form

<form id='contact-form' role="form" action="bat/MailHandler.php" method="POST">
                    <div class="contact-form-loader"></div>
                    <fieldset>
                        <div class="row">
                            <div class="grid_4">
                                <label class="name">
                                    <input id="name" class="input" name="cf_name" type="text" placeholder="Ingrese su nombre" value="" required/>
                                    <!--<span class="empty-message">*Este campo es requerido </span>
                                    <span class="error-message">*El nombre no es valido.</span>-->
                                </label>
                            </div>
                            <div class="grid_4">
                                <label class="phone">
                                    <input class="input" type="text" name="cf_phone" placeholder="Ingrese su Teléfono:" value=""/>
                                    <!--<span class="error-message">*El número no es valido.</span>-->
                                </label>
                            </div>
                            <div class="grid_4">
                                <label class="email">
                                    <input id="email" class="input" name="cf_email" type="text" placeholder="Ingrese su email" value="" required/>
                                    <!--<span class="empty-message">*Este campo es requerido.</span>
                                    <span class="error-message">*El correo no es valido.</span>-->
                                </label>
                            </div>
                        </div>
                        <label class="message">
                            <textarea id="message" class="input" name="cf_message" placeholder="Ingrese su mensaje:" 
                                      required minlength="5" maxlength="999999"></textarea>
                            <!--<span class="empty-message">*Este campo es requerido.</span>
                            <span class="error-message">*No se aceptan los siguientes caracteres: $, %, &, |. <, > y #.</span>
                        </label>-->
                        <input class="primary-btn_2" id="btn-enviar" type="submit" onclick="validate()" value="Enviar"/>    
                        <a class="primary-btn_2" href="#" data-type="reset">Nuevo</a>
                    </fieldset>
                </form>

and this is my js

            function validate{
        function email(){
            if(form.email.value == "") {
              alert("Ingresar un correo");
              form.email.focus();
              return false;
            }
            var re = /^[\w ]+$/;

            if(!re.test(form.email.value)) {
              alert("Formato de Correo invalido");
              form.email.focus();
              return false;
            }
            return true;
        }
        function name(){

           If(form.name.value == "") {
              alert("Ingrear un nombre");
              form.name.focus();
              return false;
            }
            return true;
            }               
        function msg{
                if(form.message.value == "") {
              alert("Ingrese su consulta");
              form.message.focus();
              return false;
            }
            if(!re.test(form.message.value)) {
              alert("Error, ingresar solo caracteres alfanumericos");
              form.message.focus();
              return false;
            }             

            return true;}}
        </script>
        <script>
            function validateEmail()
        {
           var emailID = document.form.email.value;
           atpos = emailID.indexOf("@");
           dotpos = emailID.lastIndexOf(".");
           if (atpos < 1 || ( dotpos - atpos < 2 )) 
           {
               alert("Por faor ingresar un formato de email valido")
               document.form.email.focus() ;
               return false;
           }
           return( true );
        }
        </script>

Can someone tell me what I'm doing wrong?

    
asked by Jorge 13.01.2017 в 20:22
source

2 answers

0
  • This: function validate { will give you a Unexpected Token . You can check it in the console of your browser.
  • This other: document.form does not serve to obtain the form, the correct thing is document.forms that returns an array with the forms in the document. It is best to select the form by id or class:

    document.getElementById('tuformid');
    
  • The reserved word if must be lowercase, because JavaScript is case sensitive. You have written:

    If(form.name.value == "")
    
  • Always use the equality operator === . Using == makes you prone to errors. Read here for more information.

  • You do not need to nest functions, you make your code less readable.

    function validate () { function email() { ... } }
    
  • You do not need to use two <scripts> tags. Your code has the same purpose.

  • If you use HTML5 validation to make a required field, then validating the same programmatically is redundant.

  • Modifying your code a bit, depending on the format you have, would look like this:

      

    Note: You can not test the code here for security reasons. However, in this fiddle you can see the code working.

    const form = document.getElementById('contact-form');
    
    form.addEventListener('submit', function (e) {
      e.preventDefault();
      // si el form es válido, envía el formulario
      if(validator.validate()) {
        form.submit();
      }
    });
    
    const validator = {
      email() {
      	const exp = /^(([^<>()\[\]\.,;:\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,}))$/;
        
        if (!exp.test(form.email.value)) {
          alert("Formato de Correo invalido");
          form.email.focus();
          return false;
        }
        return true;
      },
      phone () {
        if(!/^[0-9]/.test(form.phone.value)) {
        	alert("Solo ingrese números en el teléfono");
        }
      },
      name() {
        if (!/^[a-zA-Z]+$/.test(form.name.value)) {
          alert("Ingrese solo letras en su nombre");
          form.name.focus();
          return false;
        }
        return true;
      },
      msg() {
      	if (!/^\w+$/.test(form.message.value)) {
          alert("Error, ingresar solo caracteres alfanumericos");
          form.message.focus();
          return false;
        }
        return true;
      },
      validate () {
      	if(!this.name() || !this.phone() || !this.email() || !this.msg()) {
        	return false;
        }
        return true;
      }
    };
    <body>
      <form action="http://stackoverflow.com" id='contact-form' method="post" name="contact-form" role="form">
        <div class="contact-form-loader"></div>
        <fieldset>
          <div class="row">
            <div class="grid_4">
              <label class="name">
                <input class="input" id="name" name="cf_name" placeholder="Ingrese su nombre" type="text" value="" required>
              </label>
            </div>
            <div class="grid_4">
              <label class="phone">
                <input class="input" name="cf_phone" placeholder="Ingrese su Teléfono:" type="text" value="" required>
              </label>
            </div>
            <div class="grid_4">
              <label class="email">
                <input class="input" id="email" name="cf_email" placeholder="Ingrese su email" type="text" value="" required>
              </label>
            </div>
          </div>
          <label class="message">
            <textarea class="input" id="message" maxlength="999999" name="cf_message" placeholder="Ingrese su mensaje:" required></textarea>
          </label>
           <input class="primary-btn_2" id="btn-enviar" type="submit" value="Enviar">
          <a class="primary-btn_2" data-type="reset" href="#">Nuevo</a>
        </fieldset>
        <label class="message"></label>
      </form>
    </body>
        
    answered by 13.01.2017 / 21:43
    source
    0

    If you want the validation of html5 not to appear, there are two options:

  • Use novalidate :

          <form method="post" action="/foo" novalidate>...</form>
    
  • Do not use those validations and capture everything from js , for example:

    • required minlength
    • maxlength
    • required
  • answered by 13.01.2017 в 21:02