3

I have a form validated jQuery Validation Plugin (jqueryvalidation.org), for the phone field I use Bluefieldscom's intl-tel-input plugin but I got an issue. I got the following problems:

  • First my plugins work separately, so if I try to enter a number intl-tel-input validates it but it was not blocked for submit (argh!!) and Validation validates other fields blocking submit;
  • Then I tried to require the phone field in Validation rules, keeping validating in intl-tel-input, but the intl-tel-input worked fine only until Submit the form. Then Validation assumes control and for it if phone lenght !=0 is enough (but not for me);
  • At least, I added a condition for submit to control both if form is valid (for Validation) and if #phone is valid (and phone lenght !=0); It works, but after the submit I can't see anymore if the field is valid (for intl-tel-input) or not. How could do to show those states? I tried to add a Method to Validation Plugin, based on condition $("#phone").intlTelInput("isValidNumber"), but it doesn't shows anything (after submit).

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;
    }

        });

Thank you all.

steel
  • 11,883
  • 7
  • 72
  • 109
annydreams
  • 53
  • 1
  • 5
  • **Quote:** *"Then I tried to require the phone field in Validation rules, keeping validating in intl-tel-input"* ~ Why are you trying to use two different validation plugins at the same time? – Sparky Mar 30 '15 at 16:37
  • Beacause jQuery Validation hasn't a method to validate phone numbers with the same precision of the other plugin – annydreams Mar 30 '15 at 16:40
  • 1
    jQuery Validate has a method called `.addMethod()` for creating ***any*** custom rule you need. My best suggestion would be to use it to create a custom rule/method for jQuery Validate that is based on the actual validation function inside Bluefieldscom. Presently, you have a mess. – Sparky Mar 30 '15 at 16:41
  • Also see [the Additional Methods file](http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.1/additional-methods.js) in case there is already a rule. Otherwise, you can modify them to suit your needs, or like I stated before, take the validation function from Bluefieldscom and use that within `.addMethod()`. – Sparky Mar 30 '15 at 16:45
  • There's extacly what I tried to do, if you look at line 47 of my javascript in jsFiddle. – annydreams Mar 30 '15 at 16:46
  • No, that is not *exactly* what I mean. I am saying to get rid of the Bluefieldscom plugin entirely. Just look inside of it and take the code, the regex function, or whatever part validates for your country... then write a self-contained function for `.addMethod()`. It appears you need validation for Italian phone numbers... that Bluefieldscom plugin is really too big and complex for doing that one simple thing. – Sparky Mar 30 '15 at 16:51
  • Also, when using `addMethod()`, you're simply creating a new rule for the plugin. You would not need your custom `keydown` and `focusout` functions, as the jQuery Validate plugin handles these automatically. – Sparky Mar 30 '15 at 16:57
  • You also have a major syntax error. In the `rules` option, within `.validate()`, you have an extra `}`, which puts the second half of your rules outside of the `rules` object. Click the "Tidy Up" button in jsFiddle and the mistake becomes obvious. – Sparky Mar 30 '15 at 17:02
  • If I needed only the regex, I'd have used it. I need to validate every tipe of numbers, italian is only default (and however, regex shouldn't be enough). – annydreams Mar 30 '15 at 17:03
  • See [my comment](http://stackoverflow.com/questions/29351314/using-bluefieldscom-intl-tel-input-with-jquery-validation-plugin#comment46889316_29351314) about the misplaced `}`. That one error alone is preventing your custom `validatePhone` rule from being evaluated, because it puts `phone`, `text_message`, and `aut_privacy` outside of the `rules` object. – Sparky Mar 30 '15 at 17:08
  • Also FYI, [you should not use Allman style formatting for JavaScript](http://stackoverflow.com/q/11247328/594235). Although, in your case, you're mixing 1TBS and Allman together. Please just ***consistently*** format and indent the code so it's easier for everyone to read and quicker to find mistakes such as the misplaced brace. – Sparky Mar 30 '15 at 17:13
  • I've seen and correct the error of the misplaced `}` but now I got a syntax error in the console: _SyntaxError: Unexpected identifier 'phone'. Expected '}' to end a object literal._ ...is it because this-thing-I-didn't-got about the format? – annydreams Mar 30 '15 at 17:19

1 Answers1

3

Two problems:

  1. A closing brace was misplaced, causing three fields to be outside of the rules object within your .validate() method. See: 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. Your .validate() method was not being called at the right time as evidenced by your custom messages being ignored. I put all of the code within a DOM ready event handler.

For ease of reading and troubleshooting, I clicked the "TidyUp" button to put your code into 1TBS format.

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

Sparky
  • 98,165
  • 25
  • 199
  • 285