Jquery Validate does not work with extension type - File Input

Asked

Viewed 642 times

2

Follows 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 error:

Uncaught Typeerror: Cannot 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 does not work.

Some solution ?

  • Could be the jQuery Validate version. Downloaded from their website ?

  • Downloaded by Manage nuget Packages

  • You added the jquery.validate.methods on the page after the jquery.validate ?

  • I can’t find that name jquery.validate.methods in my script folder. Detail, downloaded straight from nuget.

1 answer

1


To work this type of validation is simple, add the Additional-methods.min.js along with jQuery and jQuery.Validation, and in its 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 to , do:

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

Reference:

Lib - jQuery.validate

  • 1

    Thank you :) Viriglio Novic

  • 1

    I put in the answer !!! @Matheusmiranda

Browser other questions tagged

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