0

I've well researched and used this, but I don't know it is still getting error. I need to check if existing image exists then file attribute should skip validation and viceversa.

HTML COde:

<input  type="file" name="image" id="image">    
<input type="hidden" name="old_image" value="">

JQuery Validation Code:

$("#add_reference").validate({
        rules: {
            link: {   
                required: true,
            },
            image:{
                //required: true,
                required: function(element) {
                    if ($("#old_image").val() == '') 
                    {
                        return true;
                    } 
                    else 
                    {
                        return false;
                    }
                },
                accept:"jpg,png,jpeg,gif"
            },
        },       
        messages: {

            link: {
                required: "Please enter link title",
            },
            image:{
                required: "Please choose image",
                accept: "Please choose valid image files",
            },
        },
        errorPlacement: function (error, element) {
            var attr_name = element.attr('name');
            error.insertAfter(element);            
        }
    });

Can Anyone tell me where I am going wrong?

5
  • 1
    What is the error you are getting? Commented Mar 5, 2018 at 12:33
  • @Ahmad Nothing validation is not prompting it Commented Mar 5, 2018 at 12:34
  • Then maybe the validation needs to be triggered by an event? Commented Mar 5, 2018 at 12:36
  • Idk that can you please help me out Commented Mar 5, 2018 at 12:36
  • try wrapping the validate function inside $(document).ready(). Commented Mar 5, 2018 at 12:37

2 Answers 2

2

There is no id in your input tag,instead you should add id attribute.

<input type="hidden" name="old_image" id="old_image" value="">

and you are calling it by id

if ($("#old_image").val() == '')
Sign up to request clarification or add additional context in comments.

Comments

1
<input  type="file" name="image" id="image">    
<input type="hidden" id="old_image" name="old_image" value="">

Your validation won't fire because it is always passing the test, you are testing if #old_image is empty and as you can see it is always empty, are you triggering an event after you upload your file???

You can do it with this event..

$(function() {
     $("input:file").change(function (){
       var fileName = $(this).val();
       $("#old_image").val(fileName);
     });
  });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.