下拉列表和表单转发器上的jQuery验证

时间:2017-09-13 18:34:45

标签: javascript

我有一个带有表单转发器的表单向导,我需要在访问下一步之前验证一个下拉列表。我尝试了不同的解决方案,并设法在第一个表单上进行验证,但它不适用于重复的表单。

JavaScript代码

if ($("body").data("title") === "admin_new_user") {

  var FormWizard = function () {

    return {
        //main function to initiate the module
        init: function () {
          if (!jQuery().bootstrapWizard) {
            return;
          }

          var form = $('#submit_form');
          var error = $('.alert-danger', form);
          var success = $('.alert-success', form);

            // Regex pe rla validazione del campo email

            $.validator.methods.email = function( value, element ) {

              return this.optional( element ) || /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$/.test( value );

            };

            // Regex la validazione del campo codice fiscale

            $.validator.methods.fiscalcode = function( value, element ) {

              return this.optional( element ) || /^(?:[B-DF-HJ-NP-TV-Z](?:[AEIOU]{2}|[AEIOU]X)|[AEIOU]{2}X|[B-DF-HJ-NP-TV-Z]{2}[A-Z]){2}[\dLMNP-V]{2}(?:[A-EHLMPR-T](?:[04LQ][1-9MNP-V]|[1256LMRS][\dLMNP-V])|[DHPS][37PT][0L]|[ACELMRT][37PT][01LM])(?:[A-MZ][1-9MNP-V][\dLMNP-V]{2}|[A-M][0L](?:[\dLMNP-V][1-9MNP-V]|[1-9MNP-V][0L]))[A-Z]$/i.test( value );

            };

            // Regex la validazione del campo numero carta d'identità e passaporto

            $.validator.methods.idcard = function( value, element ) {

              return this.optional( element ) || /^[a-z]{2}[0-9]{7}$/i.test( value );

            };

            // Regex la validazione del campo sito web

            $.validator.methods.web = function( value, element ) {

              return this.optional( element ) || /^((ftp|http|https):\/\/)?([a-zA-Z0-9]+(\.[a-zA-Z0-9]+)+.*)$/i.test( value );

            };

            //Start repeating form group add limit
              var maxGroup = 5;

              //add more fields group
              $(".addMore").click(function(){

                  if($('body').find('.fieldGroup').length < maxGroup){

                      var fieldHTML = '<div class="form-group fieldGroup">'+$(".fieldGroupCopy").html()+'</div>';
                      $('body').find('.fieldGroup:last').after(fieldHTML);

                  }else{

                      alert('Hai raggiunto il massimo numero di immobili registrabili di '+maxGroup+'');

                  }


              });

              //remove fields group
              $("body").on("click",".remove",function(){ 
                  $(this).parents(".fieldGroup").remove();
              });
          // end repeating form


            form.validate({

                doNotHideMessage: true, //this option enables to show the error/success messages on tab switch.
                errorElement: 'span', //default input error message container
                errorClass: 'help-block help-block-error', // default input error message class
                focusInvalid: false, // do not focus the last invalid input


              rules: {

                userFirst: {

                   required: true

                },

                userLast: {

                   required: true

                },

                userEmail: {

                  remote: "../controllers/ctrl_admin_user_app/check_email_validation.php",
                  required: true,
                  email: true,
                  async: false


                },

                userWeb: {

                  required: false,
                  web: true

                },

                userHometel: {

                  required: false,
                  number: true 

                },

                userMobiletel: {

                  required: false,
                  number: true 

                },

                userFiscalcode: {

                  required: true,
                  fiscalcode: true

                },

                docNum: {

                  required: {
                    depends: function () {
                        return $('#docTypo').val() == "idcard" || $('#docTypo').val() == "passport";

                    }
                  },

                  idcard: true

                },

                docTypo: {

                  required: {
                    depends: function () {
                        return $('#docNum').val() != '';

                    }
                  }

                },

                docExp: {

                    required: false,
                    dateITA : true

                },

                userBirth: {

                    required: false,
                    dateITA : true

                },

                userName: {

                    required: true, 
                    remote: "../controllers/ctrl_admin_user_app/check_user_validation.php",
                    async: false


                },

                userRole: {

                    required: true

                }


              },

   // mostro messaggi di errore personalizzati

  messages: {

    userFirst: "Ops, Il campo nome cliente è richiesto",
    userLast: "Ops, il campo cognome cliente è richiesto",

    userEmail: {

      required: "Ops, il campo email cliente è richiesto",
      email: "Ops, il formato dell'email non è corretto",
      remote: "Ops, questo indirizzo email esiste già, per favore scegline un altro!"

    },

    userWeb: {

      web: "Ops, il formato del sito web non è corretto"

    },

    userHometel: {

      number: "Ops, il formato del numero non è corretto!"

    },

    userMobiletel: {

      number: "Ops, il formato del numero non è corretto!"

    },

    userFiscalcode: {

      required: "Ops, il campo codice fiscale è richiesto",
      fiscalcode: "Ops, il formato codice fiscale non è corretto"

    },

    docNum: {

      required: "Ops, non ha secificato il numero di documento",
      idcard: "Ops il numero del documento non è un formato valido"

    },

    docTypo:{

      required: "Ops, seleziona tipologia documento",


     },

    docExp: {

      dateITA : "Ops, Il formato data deve essere nel formato giorno/mese/anno"

    },

    userBirth: {

      dateITA : "Ops, Il formato data deve essere nel formato giorno/mese/anno"

    },

    userName: {

      required: "Ops, devi inserire un nome utente per il cliente!",
      remote: "Ops, questo nome utente già esiste, per favore scegline un altro!"

    },

    userRole: {

      required: "Ops, il campo ruolo cliente è richiesto!"

    }

  },

  errorPlacement: function (error, element) { // render error placement for each input type

          error.insertAfter(element); // for other inputs, just perform default behavior

        },

  invalidHandler: function (event, validator) { //display error alert on form submit   
    success.hide();
    error.show();
    App.scrollTo(error, -200);
  },

  highlight: function (element) { // hightlight error inputs
    $(element)
          .closest('.form-group').removeClass('has-success').addClass('has-error'); // set error class to the control group
        },

  unhighlight: function (element) { // revert the change done by hightlight
    $(element)
          .closest('.form-group').removeClass('has-error'); // set error class to the control group
        },

  // success: function (label) {

  //   label
  //       .addClass('valid') // mark the current input as valid and display OK icon
  //   .closest('.form-group').removeClass('has-error').addClass('has-success'); // set success class to the control group

  // },

  submitHandler: function (form) {

    //add here some ajax code to submit your form 
    $.ajax({

      url: form.action,
      type: form.method,
      data: $(form).serialize(),

     // se tutto va a buon fine mostro un messaggio di successo utilizzando sweetalert

      success: function(response) {

        swal({

            title: response.title,
            text: response.message,
            type: response.status

          },

          function(){ 

            location.reload();

          }

        );

      },

      error: function(jqXHR, exception) {

        if (jqXHR.status === 0) {

          swal('Il server non risponde', 'Siamo spiacenti non è stato possibile eseguire questa operazione, per favore contatta l\'amministratore di sistema.', 'info');

        } else if (jqXHR.status == 404) {

          swal('Errore 404', 'Siamo spiacenti non è stato possibile eseguire questa operazione, per favore contatta l\'amministratore di sistema.', 'info');

        } else if (jqXHR.status == 500) {

          swal('Errore 500', 'Siamo spiacenti non è stato possibile eseguire questa operazione, per favore contatta l\'amministratore di sistema.', 'info');

        } else if (exception === 'parsererror') {

          swal('Si è verificato un errore!', 'Siamo spiacenti non è stato possibile eseguire questa operazione, per favore contatta l\'amministratore di sistema.', 'info');

        } else if (exception === 'timeout') {

          swal('Time Out', 'Siamo spiacenti non è stato possibile eseguire questa operazione, per favore contatta l\'amministratore di sistema.', 'info');

        } else if (exception === 'abort') {

          swal('Richiesta Annullata', 'Siamo spiacenti non è stato possibile eseguire questa operazione, per favore contatta l\'amministratore di sistema.', 'info');

        } else {

          swal('Errore non previsto', 'Siamo spiacenti non è stato possibile eseguire questa operazione, per favore contatta l\'amministratore di sistema.', 'info');
        }

      }  

    });

  }

});


var handleTitle = function(tab, navigation, index) {


  var total = navigation.find('li').length;
  var current = index + 1;
                // set wizard title
                // $('.step-title', $('#form_wizard_1')).text('Step ' + (index + 1) + ' of ' + total);
                // set done steps
                jQuery('li', $('#form_wizard_1')).removeClass("done");
                var li_list = navigation.find('li');
                for (var i = 0; i < index; i++) {
                  jQuery(li_list[i]).addClass("done");
                }

                if (current == 1) {
                  $('#form_wizard_1').find('.button-previous').hide();
                } else {
                  $('#form_wizard_1').find('.button-previous').show();
                }

                if (current >= total) {
                  $('#form_wizard_1').find('.button-next').hide();
                  $('#form_wizard_1').find('.button-submit').show();

                } 

                App.scrollTo($('.page-title'));
              }

            // default form wizard
            $('#form_wizard_1').bootstrapWizard({
              'nextSelector': '.button-next',
              'previousSelector': '.button-previous',

              onTabClick: function (tab, navigation, index, clickedIndex) {
                return false;

                success.hide();
                error.hide();
                if (form.valid() == false) {
                  return false;
                }

                handleTitle(tab, navigation, clickedIndex);
              },

              onNext: function (tab, navigation, index) {
                success.hide();
                error.hide();

                if (form.valid() == false) {
                  return false;
                }

                // validation on dropdown
                $("#userGruppo").each(function () {
              $(this).rules('add', {
                  required: true
              });
            });

                handleTitle(tab, navigation, index);

              },

              onPrevious: function (tab, navigation, index) {
                success.hide();
                error.hide();

                handleTitle(tab, navigation, index);
              },

              onTabShow: function (tab, navigation, index) {
                var total = navigation.find('li').length;
                var current = index + 1;
                var $percent = (current / total) * 100;
                $('#form_wizard_1').find('.progress-bar').css({
                  width: $percent + '%'
                });
              }
            });

            $('#form_wizard_1').find('.button-previous').hide();

            $('#form_wizard_1 .button-submit').click(function () {
              if (form.valid() == false) {
                return false;
              }

            }).hide();

            //apply validation on select2 dropdown value change, this only needed for chosen dropdown integration.
            $('#userRole', form).change(function () {
                form.validate().element($(this)); //revalidate the chosen dropdown value and show error or success message for the input
              });

           }

         };

       }();

       jQuery(document).ready(function() {
        FormWizard.init();
      });


     }

0 个答案:

没有答案