Validating Form with JQUERY Validation + Masks

Asked

Viewed 14,523 times

2

I am developing an html form validation plugin for CPF, ZIP, DATA, PHONE.

I was able to find one that adds a method to CPF in Jquery Validation, but I’m having trouble editing the code and making it work for the other fields:

Can you give me some example of how I would do ?

UPDATE: PROBLEM SOLVED !! And it was: the scripts I was using used a certain type of

quote " while the rest of my code was " .

ADDMETHOD

            jQuery.validator.addMethod("cpf", function(value, element) {
           value = jQuery.trim(value);
            value = value.replace('.','');
            value = value.replace('.','');
            cpf = value.replace('-','');
            while(cpf.length < 11 ) cpf = "0"+ cpf;  
            var expReg = /^0+$|^1+$|^2+$|^3+$|^4+$|^5+$|^6+$|^7+$|^8+$|^9+$/;
            var a = [];
            var b = new Number;
            var c = 11;
            for (i=0; i<11; i++){
                a[i] = cpf.charAt(i);
                if (i < 9) b += (a[i] * --c);
            }
            if ((x = b % 11) < 2) { a[9] = 0 } else { a[9] = 11-x }
            b = 0;
            c = 11;
            for (y=0; y<10; y++) b += (a[y] * c--);
            if ((x = b % 11) < 2) { a[10] = 0; } else { a[10] = 11-x; }

            var retorno = true;
            if ((cpf.charAt(9) != a[9]) || (cpf.charAt(10) != a[10]) || cpf.match(expReg)) retorno = false;

            return this.optional(element) || retorno;

        }, "Informe um CPF válido");


        $(document).ready(function(){

           $("#formH2H").validate({
              rules: {
                  cpf: {cpf: true, required: true}
              },
              messages: {
                 cpf: { cpf: 'CPF inválido'}
              }
              ,submitHandler:function(form) {
                 alert('Muito bem, as informações estão corretas.');
              }
           });
        });

I just stopped there. I tried to look at plugins in javascript, I even found some that work, but it is very strange because one inserts a text under the field and another opens an Alert..

And to add a mask to the inputs, I also found some on the internet, but in my code are not working.

MASKS

jQuery(function($){
       $("#date").mask("99/99/9999");

       $("#tel").mask("(999) 999-9999");
});

Fiddle

NOTE: I need the formatting and the mask to be totally done via Jquery or Javascript, not being able to count with html, I need to call each id of the field, and format and validate it.

EDIT:

So the problem is that you need to do the formatting and masking for any form.. in the case you showed, I would need to change the html, which is not the intention. as I would pass them to parameters you put in html, right in . js ?

2 answers

2

  • Have some example to show?

2


UPDATE

For mask you can use this plugin Masked Input Pluguin for jQuery.

You need to download the file and install it in your directory, and then make the call in HTML:

<script src="jquery.js" type="text/javascript"></script>
<script src="jquery.maskedinput.js" type="text/javascript"></script>

And then just add the ids from the form in the script, changing the rules as needed, for example (see below on executing code snippet):

   $("#phone").mask("(999) 999-9999");
   $("#date").mask("99/99/9999");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script src="https://rawgit.com/digitalBush/jquery.maskedinput/1.4.0/dist/jquery.maskedinput.js"></script>
Data
<br>
<input type="text" id="date">
<br>
Fone
<br>
<input type="text" id="phone">

/UPDATE

For masks of ZIP, ID, CPF and date, I’ve used this in pure JS:

// máscara de cep rg, cpf etc
function formatar(mascara, documento){
    var i = documento.value.length;
    var saida = mascara.substring(0,1);
    var texto = mascara.substring(i)
    if (texto.substring(0,1) != saida){
        documento.value += texto.substring(0,1);
    }
}
<label for="Cep"> CEP: </label>
      <input type="text" size="8" id="Cep" maxlength="9" OnKeyPress="formatar('#####-###', this)">
<br>
<label id="data">Data de Nascimento:</label>
      <label for="Cdata"></label>
        <input type="text" name="data" id="data" size="9" maxlength="10" OnKeyPress="formatar('##/##/####', this)">
<br>
      <label for="Cpf"> CPF:</label>
      <input type="text" id="Cpf" size="12" maxlength="14"  OnKeyPress="formatar('###.###.###-##', this)"/>
<br>
      <label for="Crg"> RG:</label>
      <input type="text" name="Trg" id="Crg" size="12" maxlength="14" OnKeyPress="formatar('##.###.###-##', this)">

But today I’m wearing the jQureyMask.

For phone has an excellent topic here: How to differentiate phone types

For validation you can use the Jqueryvalidator or the HTML5 validation system itself (but not compatible with older browsers).

For example:

<form action="" method="post">
  <p>regexp: <br> <input type="text" name="regexp"pattern="[A-Z-a-z0-9]{10}" required></p>
  <p>email: <br> <input type="email" name="email" required></p>
  <p>url: <br> <input type="url" name="url" required ></p>
  <p>number: <br> <input type="number" name="number" required></p>
  <p>tel: <br> <input type="tel" name="tel" required></p>
  <p>date: <br> <input type="date" name="date" required></p>
  <p>datetime: <br> <input type="datetime" name="datetime" required></p>
  <p>datetime-local: <br> <input type="datetime-local" name="datetime-local" required></p>
  <p>month: <br> <input type="month" name="month" required></p>
  <p>week: <br> <input type="week" name="week" required></p>
  <p>color: <br> <input type="color" name="color" required></p>
  <p>time: <br> <input type="time" name="time" required></p>
  <p>search: <br> <input type="search" name="search" required></p>
  <p>range: <br> <input type="range" min="0" max="5" value="1" name="range" required></p>
  <p><input type="submit" Value="Enviar"></p>
</form>

Sources:

http://www.tutsup.com/2014/08/28/formularios-html5/

http://blog.naison.com.br/jquery/valide-seus-formularios-com-jquery-validator

See also:

  • So the problem is that you need to do the formatting and masking for any form.. in the case you showed, I would need to change the html, which is not the intention. how I would pass them to parameters you put in html, right in . js ?

  • Ah, now that I saw the remark in the op... it was bad, if the moderation wants to erase blz... btw, also interested in a solution like this, it seems much more elegant even. :)

  • But then you want the . js script to "guess" what each <input type "text" > field is. For example, the zip code is XXXXX-XXX, the CPF is XXX.XXX.XXX-XX, each has a format, as the js will know which format to use in each field (both for mask and validation), if you do not report in html? That’s possible?

  • by id.. CPF will always be CPF, phone will always be phone.. that’s the idea.

  • Ah got it. For validation I do not know, but for mask maybe this plugin is useful: http://digitalbush.com/projects/masked-input-plugin/ I edited the answer, including this plugin.

  • So, I already include. I tried several scripts, but nothing.. they seem to conflict when I call "Cpf" for example twice in two functions, all for.. follow the link http://jsfiddle.net/5wkjbu8c/7/

  • I found the same question in Stackoverflow.com, follow the link: http://stackoverflow.com/questions/4399086/conflict-between-jquery-validate-and-masked-input

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.