Jquery Validate does not work with extension type - File Input

2

Follow the code:

$(document).ready(function () {
            $("#myform").validate({
                ignore: ":hidden",
                rules: {

                    images: { required: true, extension: "jpg"},
                    messages: { 
                    images: Arquivo inválido}
                    },
                    submitHandler: function (form) {


                        ajax - post ....

                    }                   
            }
}

Html:

<input type="file" id="image_preview" class="form-control" name="images" accept="image/*">

I use this bootstrap fileinput

After choosing an image, I get an error:

  

Uncaught TypeError: Can not read property 'call' of undefined.   Exception occurred when checking element image_preview, check the   'extension' method.

If I leave only "{ required: true}" it works as the required field. With the extension type it does not work.

Any solution?

    
asked by anonymous 18.01.2017 / 21:57

1 answer

1

To work with this type of validation is simple, add the additional-methods.min.js along with jQuery and jQuery.Validation , and in your validation include extension with the types you want to check, in the example I put jpg|jpeg|gif , but that's up to you.

Example:

Form

<form id="form1" name="form1" method="post">
  <div>
    <label> Digite o nome:
      <input type="text" name="tname" />
    </label>
  </div>
  <div>
    <label> Escolha a Foto:
      <input type="file" name="tfoto" id="tfoto" />
    </label>
  </div>
  <button>Enviar</button>
</form>

Javascript

$(document).ready(function()
{
    $("#form1").validate({
        ignore: ":hidden",
      rules: {
        tname : {
            required : true
        },
        tfoto : {
            required : true,
            extension: "jpg|jpeg|gif"
        }
      },
      messages: {
        tname : {
            required : 'Digite o nome'
        },
        tfoto : {
            required : 'Escolha a foto',
            extension: 'Foto do tipo inválida'
        }
      }
  });

  $("#tfoto").filestyle();
});

Example - jsfiddle.net

To add the reference in the , do:

bundles.Add(new ScriptBundle("~/bundles/jqueryval")
         .Include("~/Scripts/jquery.validate*","~/Scripts/additional-methods.min.js"));

Reference:

Lib - jQuery.validate

    
18.01.2017 / 23:16