Validate a tagsinput field of emails with jquery validate

0

I have a field with which the user adds several email addresses and they are saved in tags. The plugin I use for this is the bootstrap tagsinput. It would be necessary to validate each tag as an email. The html of the field is the following:

<input class="form-control" data-role="tagsinput" id="email" placeholder="Introduce una dirección email válida" name="email" type="text" style="display: none;">

When I save this field in the database, what it returns is something similar to the following: email1 @ test.com, email2 @ test.com, ...

And what it rides in html is:

<div class="bootstrap-tagsinput">
<span class="tag label label-info">[email protected] <span data-role="remove"></span>
</span> <span class="tag label label-info">[email protected] <span data-role="remove"></span>
</span> <span class="tag label label-info">[email protected] <span data-role="remove"></span></span> 
<input type="text" placeholder="Introduce una dirección email válida" size="36">

In other words, what interests me is validating each of those span with jquery validate but I can not find the way. Some help? Thanks.

    
asked by Jose 28.02.2018 в 19:12
source

1 answer

0

In response to the problem you present, you must know in advance that the tags plugin you use hides the true field that you are validating, so you have to take this into account when validating since by default jquery-validate ignores the fields hidden. Knowing this you can follow my example

This is the html, I do not put the libraries because they are the same ones you use

<div class="container">
    <form method="post">
        <input type="text" name="campo1" id="campo1" data-role="tagsinput"/>
        <input type="submit" value="OK"/>
    </form>
</div>

Now the javascript code

<script>
    //Añado un nuevo método a las reglas de validación de jquery validate
    $.validator.addMethod( "tag_email", function( value, element, params ){
        //Si el elemento es opcional devuelvo true para no validarlo
        if(this.optional(element)){
          return true;
        }
        /*Como me has dicho que el valor que se almacena en la base de datos
        es de la forma [email protected],[email protected] separo este texto por
        los delimitadores */
        var parts = value.split(',');
        //Creo esta variable para detener el ciclo siguiente cuando no es un correo válido
        var fail = false;
        //Recorro la lista de los correos
        for(var i in parts){
            /*Verifico que sea una dirección de correo correcta, es la misma
              expresión regular que usa esta librería para la regla email */
            if(/^[a-zA-Z0-9.!#$%&'*+\/=?^_'{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(parts[i].trim()) === false){
              //Si falla la verificación pongo a true esta variable y salgo del ciclo
              fail = true;
              break;
            }
        }
        //Devuelve true si el elemento a validar es opcional o si no hay ningun fallo cuando valida los correos contenidos en su valor
        return this.optional(element) || !fail;
    //Este es el mensaje de error que voy a devolver
    }, "Existen direcciones de correo incorrectas");

  /* Con esto valido mi formulario observar que puse ignore en "" ya que
  inicialmente es ":hidden" y agregué la nueva regla tag_email */
  $('form').validate({
    ignore: "",
    rules: {
         'campo1': {
            required: true,
            tag_email: true
         }
     }
  });

 //Omití el inicializador del tagsinput no tiene relevancia en este problema

I hope it works if you need something else I can make you a fiddle in case it does not work for you, although I've already tried it. Greetings

    
answered by 28.02.2018 / 22:12
source