Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make file upload field mandatory

Hello can anyone plz fix this problem.

my input field is below code and I am doing validation on form submit i.eis:

<input name="file[]" type="file" multiple="multiple">

<form name="bdmrequest" enctype="multipart/form-data" method="post"  action="<?php echo $_SERVER["PHP_SELF"];?>" onsubmit="return(validate());">

i have included validate.js in header and i am able to do validation of other fields except file upload. validation code i am using:

if(document.bdmrequest.file.value== "")
  {
   alert("Attachment Required");
   document.bdmrequest.file.focus();
    return false;
  } 

js doesn't support me to use (document.bdmrequest.file[].value== "") please suggest me the alternatives. the name of my input type has to be file[] only.

like image 930
user3367831 Avatar asked May 30 '14 07:05

user3367831


People also ask

How can I make a file upload mandatory?

No need of JavaScript validation you can use "required" attribute in input type.... The HTML5 required attribute marks any input/textarea as being required to have a value before the form can be submitted.

How do you make an input text field mandatory for data entry?

Required attribute: If you want to make an input mandatory to be entered by the user, you can use the required attribute. This attribute can be used with any input type such as email, URL, text, file, password, checkbox, radio, etc. This can help to make any input field mandatory.

What is file upload validation?

File Extension Validation This is basically where you are checking the extension of the presented file and making sure it is one that you should be accepting. This check is non-trivial, as there are multiple ways to evade this filtering depending on how you are implementing it.


3 Answers

If you need pure Javascript: Demo Fiddle

function validate(){
    var inp = document.getElementById('upload');
    if(inp.files.length === 0){
        alert("Attachment Required");
        inp.focus();

        return false;
    }
}

jQuery:

function validate(){

    if($('#upload')[0].files.length === 0){
        alert("Attachment Required");
        $('#upload').focus();

        return false;
    }
}
like image 112
Shaunak D Avatar answered Oct 09 '22 15:10

Shaunak D


No need of JavaScript validation you can use "required" attribute in input type....

 <input type="file" required="required">
like image 31
Dileep Kumar Avatar answered Oct 09 '22 14:10

Dileep Kumar


You can check if the value is empty.

<input name="file[]" type="file" multiple="multiple" id="uploadField">

And then in js:

if($("#uploadField").val() != ""){
      //your success code here
}
like image 21
Alex Char Avatar answered Oct 09 '22 16:10

Alex Char