使用Bluefieldscom intl-tel-input和jQuery Validation Plugin

时间:2015-03-30 16:22:42

标签: jquery forms validation jquery-validate intl-tel-input

我有一个经过表单验证的jQuery Validation Plugin(jqueryvalidation.org),对于电话字段我使用Bluefieldscom's intl-tel-input plugin但是我遇到了问题。 我遇到了以下问题:

  • 首先我的插件单独工作,所以如果我尝试输入一个数字intl-tel-input验证它,但它没有被阻止提交(argh !!)并且验证验证阻止提交的其他字段;
  • 然后我尝试在验证规则中要求电话字段,在intl-tel-input中保持验证,但是intl-tel-input只在提交表单之前工作正常。然后验证假定控制,如果电话长度!= 0就足够了(但不适合我);
  • 至少,我添加了一个提交条件来控制表单是否有效(用于验证)和#phone是否有效(和电话长度!= 0); 它可以工作,但是在提交之后我不能再看到该字段是否有效(对于intl-tel-input)。 怎么能显示这些状态? 我尝试根据条件$(" #phone")。intlTelInput(" isValidNumber")添加一个方法到验证插件,但它没有显示任何内容(提交后) )。

This is my code on jsFiddle

<fieldset id="richiedi">
<form action="" method="POST" name="WebToLeadForm" method="POST" id="WebToLeadForm" class="form-horizontal col-md-11">
<input type="hidden" name="oid">

<p>&nbsp;</p>
<p><b>Per essere contattato da un commerciale</b>, compila il form sottostante. I campi richiesti sono obbligatori.<br /></p>


<div class="form-group">
  <label class="col-md-3 control-label" for="first_name">Nome:</label>
  <div class="col-md-9">
    <input class="form-control" id="first_name" name="first_name" maxlength="40" tabindex="1" type="text">
     <span class="glyphicons form-control-feedback" aria-hidden="true"></span>
  </div>
</div>
 <div class="form-group">
      <label class="col-md-3 control-label" for="last_name">Cognome:</label>
     <div  class="col-md-9">
         <input class="form-control" id="last_name" name="last_name" maxlength="80" tabindex="2" type="text">
        <span class="glyphicons form-control-feedback" ></span>
     </div>
 </div>
 <div class="form-group">
      <label class="col-md-3 control-label" for="company">Azienda:</label>
      <div  class="col-md-9">
        <input class="form-control" id="company" name="company" maxlength="40" tabindex="3" type="text">
        <span class="glyphicons form-control-feedback" aria-hidden="true"></span>
      </div>
 </div>

<input type="hidden" name="city" value="">

 <div class="form-group">
      <label class="col-md-3 control-label" for="state">Provincia:</label>
      <div  class="col-md-9">



<select class="form-control" id="state" name="state" title="Provincia" tabindex="4">
    <option disabled selected value="">--Scegli dalla lista--</option>
    <option value="AGRIGENTO">AGRIGENTO</option>
    <option value="ALESSANDRIA">ALESSANDRIA</option>
    <option value="ANCONA">ANCONA</option>
    <option value="AOSTA">AOSTA</option>
    <option value="AREZZO">AREZZO</option>
    <option value="ASCOLI PICENO">ASCOLI PICENO</option>
    <option value="ASTI">ASTI</option>
    <option value="AVELLINO">AVELLINO</option>
    <option value="BARI">BARI</option>
    <option value="BARLETTA-ANDRIA-TRANI">BARLETTA-ANDRIA-TRANI</option>
    <option value="BELLUNO">BELLUNO</option>
    <option value="BENEVENTO">BENEVENTO</option>
    <option value="BERGAMO">BERGAMO</option>
    <option value="BIELLA">BIELLA</option>
    <option value="BOLOGNA">BOLOGNA</option>
    <option value="BOLZANO">BOLZANO</option>
    <option value="BRESCIA">BRESCIA</option>
    <option value="BRINDISI">BRINDISI</option>
    <option value="CAGLIARI">CAGLIARI</option>
    <option value="CALTANISSETTA">CALTANISSETTA</option>
    <option value="CAMPOBASSO">CAMPOBASSO</option>
    <option value="CARBONIA-IGLESIAS">CARBONIA-IGLESIAS</option>
    <option value="CASERTA">CASERTA</option>
    <option value="CATANIA">CATANIA</option>
    <option value="CATANZARO">CATANZARO</option>
    <option value="CHIETI">CHIETI</option>
    <option value="COMO">COMO</option>
    <option value="COSENZA">COSENZA</option>
    <option value="CREMONA">CREMONA</option>
    <option value="CROTONE">CROTONE</option>
    <option value="CUNEO">CUNEO</option>
    <option value="ENNA">ENNA</option>
    <option value="FERMO">FERMO</option>
    <option value="FERRARA">FERRARA</option>
    <option value="FIRENZE">FIRENZE</option>
    <option value="FOGGIA">FOGGIA</option>
    <option value="FORLÌ-CESENA">FORLÌ-CESENA</option>
    <option value="FROSINONE">FROSINONE</option>
    <option value="GENOVA">GENOVA</option>
    <option value="GORIZIA">GORIZIA</option>
    <option value="GROSSETO">GROSSETO</option>
    <option value="IMPERIA">IMPERIA</option>
    <option value="ISERNIA">ISERNIA</option>
    <option value="LA SPEZIA">LA SPEZIA</option>
    <option value="L'AQUILA">L'AQUILA</option>
    <option value="LATINA">LATINA</option>
    <option value="LECCE">LECCE</option>
    <option value="LECCO">LECCO</option>
    <option value="LIVORNO">LIVORNO</option>
    <option value="LODI">LODI</option>
    <option value="LUCCA">LUCCA</option>
    <option value="MACERATA">MACERATA</option>
    <option value="MANTOVA">MANTOVA</option>
    <option value="MASSA-CARRARA">MASSA-CARRARA</option>
    <option value="MATERA">MATERA</option>
    <option value="MEDIO CAMPIDANO">MEDIO CAMPIDANO</option>
    <option value="MESSINA">MESSINA</option>
    <option value="MILANO">MILANO</option>
    <option value="MODENA">MODENA</option>
    <option value="MONZA-BRIANZA">MONZA-BRIANZA</option>
    <option value="NAPOLI">NAPOLI</option>
    <option value="NOVARA">NOVARA</option>
    <option value="NUORO">NUORO</option>
    <option value="OGLIASTRA">OGLIASTRA</option>
    <option value="OLBIA-TEMPIO">OLBIA-TEMPIO</option>
    <option value="ORISTANO">ORISTANO</option>
    <option value="PADOVA">PADOVA</option>
    <option value="PALERMO">PALERMO</option>
    <option value="PARMA">PARMA</option>
    <option value="PAVIA">PAVIA</option>
    <option value="PERUGIA">PERUGIA</option>
    <option value="PESARO-URBINO">PESARO-URBINO</option>
    <option value="PESCARA">PESCARA</option>
    <option value="PIACENZA">PIACENZA</option>
    <option value="PISA">PISA</option>
    <option value="PISTOIA">PISTOIA</option>
    <option value="PORDENONE">PORDENONE</option>
    <option value="POTENZA">POTENZA</option>
    <option value="PRATO">PRATO</option>
    <option value="RAGUSA">RAGUSA</option>
    <option value="RAVENNA">RAVENNA</option>
    <option value="REGGIO CALABRIA">REGGIO CALABRIA</option>
    <option value="REGGIO EMILIA">REGGIO EMILIA</option>
    <option value="RIETI">RIETI</option>
    <option value="RIMINI">RIMINI</option>
    <option value="ROMA">ROMA</option>
    <option value="ROVIGO">ROVIGO</option>
    <option value="SALERNO">SALERNO</option>
    <option value="SASSARI">SASSARI</option>
    <option value="SAVONA">SAVONA</option>
    <option value="SIENA">SIENA</option>
    <option value="SIRACUSA">SIRACUSA</option>
    <option value="SONDRIO">SONDRIO</option>
    <option value="TARANTO">TARANTO</option>
    <option value="TERAMO">TERAMO</option>
    <option value="TERNI">TERNI</option>
    <option value="TORINO">TORINO</option>
    <option value="TRAPANI">TRAPANI</option>
    <option value="TRENTO">TRENTO</option>
    <option value="TREVISO">TREVISO</option>
    <option value="TRIESTE">TRIESTE</option>
    <option value="UDINE">UDINE</option>
    <option value="VARESE">VARESE</option>
    <option value="VENEZIA">VENEZIA</option>
    <option value="VERBANO-CUSIO-OSSOLA">VERBANO-CUSIO-OSSOLA</option>
    <option value="VERCELLI">VERCELLI</option>
    <option value="VERONA">VERONA</option>
    <option value="VIBO VALENTIA">VIBO VALENTIA</option>
    <option value="VICENZA">VICENZA</option>
    <option value="VITERBO">VITERBO</option>
</select>
      </div>
 </div>
  <div class="form-group">
     <label class="col-md-3 control-label" for="email">Email:</label>
     <div class="col-md-9">
        <input class="form-control" id="email" name="email" maxlength="80" tabindex="5" type="text">
        <span class="glyphicons form-control-feedback" aria-hidden="true"></span>
     </div>
 </div>

 <div class="form-group">
     <label class="col-md-3 control-label" for="phone">Telefono:</label>
     <div class="col-md-9">

        <input class="form-control required" id="phone" name="phone" type="tel" tabindex="6">
        <span class="glyphicons form-control-feedback" aria-hidden="true"></span>
<small id="valid-msg" class="hide help-block">✓ Numero di telefono valido</small>
<small id="error-msg" class="hide help-block">Numero di telefono non valido</small>
     </div>
 </div>

<input type="hidden" name="lead_source" value="Sito Web"><!--Fonte del lead-->

<div class="form-group">
     <label class="col-md-3 control-label" for="text_message"> Messaggio:</label>
     <div  class="col-md-9"> 
         <textarea class="form-control required"  id="text_message" name="text_message" tabindex="7" rows="5" cols="30" wrap="soft"></textarea><!--00Nw00000088clXEAQ-->
         <span class="glyphicons form-control-feedback" aria-hidden="true"></span>
     </div>
</div>


<div class="form-group text-center">
  <div class="col-md-3 text-right col-xs-2">
    <input class="check required" type="checkbox" id="aut_privacy" tabindex="8" name="aut_privacy">
  </div>
  <label class="col-md-9 text-left col-xs-10" for="aut_privacy">*Autorizzo il trattamento dei miei dati personali.<br />

    <span class="glyphicons form-control-feedback" aria-hidden="true"></span>
  </label></div>

<input type="hidden" name="00Nw00000088clXEAQ" id="00Nw00000088clXEAQ" value="">
<button class="btn btn-default pull-right btn-lg col-xs-12 col-sm-4"name="Submit" id="submit" tabindex="16">Invia</button>

</form>
<script type="text/javascript">
     $("#phone").intlTelInput({
    //allowExtensions: true,
    //autoFormat: false,
    //autoHideDialCode: false,
    autoPlaceholder: false,
    defaultCountry: "it",
    //ipinfoToken: "yolo",
    //nationalMode: false,
    //numberType: "MOBILE",
    //onlyCountries: ['us', 'gb', 'ch', 'ca', 'do'],
    preferredCountries: ['it'],
    utilsScript: "https://img.infocert.it/js/libphonenumber.js"
  });

var telInput = $("#phone"),
  errorMsg = $("#error-msg"),
  validMsg = $("#valid-msg");

// on blur: validate
telInput.focusout(function() {
  if ($.trim(telInput.val())) {
    if (telInput.intlTelInput("isValidNumber")) {
      validMsg.removeClass("hide");
    } else {
      telInput.addClass("error");
      errorMsg.removeClass("hide");
      validMsg.addClass("hide");
    }
  }
  var numberType = $("#phone").intlTelInput("getNumberType");
  if (numberType == intlTelInputUtils.numberType.MOBILE) {
    // is a mobile number
    $("#phone").attr('name', 'mobile');
  }else{
    $("#phone").attr('name', 'phone');
  }
});

// on keydown: reset
telInput.keydown(function() {
  telInput.removeClass("error");
  errorMsg.addClass("hide");
  validMsg.addClass("hide");
});
$("#text_message").focusout(function(){$("#00Nw00000088clXEAQ").val($("#text_message").val())})

    jQuery.validator.addMethod('validatePhone', function() {
            if ($("#phone").intlTelInput("isValidNumber")){
                return true;
                }
            else{
                    return false;
                }
                }, "Numero non valido");

$(window).load(function()  { 
    $("#WebToLeadForm").validate(  
    {  
        errorElement: 'small', 
        errorClass: 'help-block',
        errorPlacement: function(error, element) {
            if (element.attr("name") == "aut_privacy" ) {
              error.insertBefore(element.parent());
            }else {
              error.insertAfter(element);
            }
          },
        rules:  
        {  
        first_name:{  
            required: true,  
            minlength: 2  
            },
        last_name:{  
            required: true,  
            minlength: 2  
            },
        company:{
            required:true
        }, 
        state:{
            required:true
        },  
        email:{  
            required: true,  
            email: true  
            }  
        }, 
        phone:{  
            required: true,
            validatePhone: true
        }, 
        text_message:{
            required:true,
            minlength : 20
        },
        aut_privacy:{
            required:true,
        },
        messages:  
        {  
        first_name:{  
            required: "Inserire il proprio nome",  
            minlength: "Inserire il proprio nome"  
            },  
        last_name:{  
            required: "Inserire il proprio cognome",  
            minlength: "Inserire il proprio cognome"  
            }, 
        company:"Fornire il nome dell'azienda",
        state:"",  
        email:{  
            required: "Inserire la propria e-mail per ottenere un contatto",  
            email: "L'indirizzo e-mail non è valido!"  
            },

        phone:"Fornire il nome dell'azienda",
        text_message:"Spiegaci brevemente la tua situazione", 
        aut_privacy:"È necessaria l'autorizzazione al trattamento dei dati"
        }, 
         highlight: function (element) {

                $(element).closest('.form-group').removeClass('has-success').addClass('has-error');
                $(element).siblings().filter('.glyphicons').removeClass('ok_2').addClass('remove_2');

            },
          unhighlight: function (element) {
                $(element).closest('.form-group').removeClass('has-error').addClass('has-success');
                $(element).siblings().filter('.glyphicons').removeClass('remove_2').addClass('ok_2');

            } 


    });   


  });

$('#submit').click(function(){
    if ($("#WebToLeadForm").valid() && $('#phone').val().length != 0 && $("#phone").intlTelInput("isValidNumber")){
        alert('$("#WebToLeadForm").submit()')
        }
    else {
        alert('Errore');

        return false;
    }

        });

谢谢大家。

1 个答案:

答案 0 :(得分:1)

两个问题:

  1. 右括号错位,导致三个字段位于rules方法中的.validate()对象之外。请参阅:http://jsfiddle.net/g6cbsh1b/

    rules: {
        first_name: {
            required: true,
            minlength: 2
        },
        last_name: {
            required: true,
            minlength: 2
        },
        company: {
            required: true
        },
        state: {
            required: true
        },
        email: {
            required: true,
            email: true
        } // <-- EXTRA BRACE
    },
    phone: {
        required: true,
        validatePhone: true
    },
    text_message: {
        required: true,
        minlength: 20
    },
    aut_privacy: {
        required: true,
        // <-- MISSING A BRACE
    },
    
  2. 您的.validate()方法未在正确的时间被调用,因为您的自定义消息被忽略了。我将所有代码放在DOM ready事件处理程序中。

  3. 为了便于阅读和排除故障,我点击了“TidyUp”按钮将您的代码转换为1TBS格式。

    DEMO:https://jsfiddle.net/fyo4ubvf/2/