13

This is my code:

 <label for="uploadFile" class="custom-uploadFile">
    <i class="fa fa-cloud-upload"></i> UPLOAD ID
  </label>
  <input class="form-control input-lg"  name="picture" id="uploadFile" type="file" style="display:none;" required>

I want to let this upload field be required, but the input is hidden.

I must use some JavaScript. Or what can I use to solve this problem? I watched a lot of tutorials, but they did not work!

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131

3 Answers3

23

If you want to see the form validation message you can hide the input using opacity.

#uploadFile {
  opacity: 0;
  width: 0;
  float: left; /* Reposition so the validation message shows over the label */
}

div {
    text-align: center;
}
<form>
<input name="picture" id="uploadFile" type="file" required>

<label for="uploadFile">Upload label</label>
    
<div><input  name="submit" type="submit"></div>
</form>
Jarzon
  • 615
  • 1
  • 6
  • 16
  • 2
    the form element now no longer HIDDEN, it just INVISIBLE. "hidden" input take no space on the form, while the "invisible" input still took space (width/height) in the form – Toni Tegar Sahidi Jan 23 '19 at 03:39
  • 1
    You can't just make the input hidden since that's gonna also hide the validation message, but there is a few hacks you can probably use to better mimic a hidden input with pros/cons. – Jarzon Jan 24 '19 at 01:46
  • I added width: 0; so the input doesn't take width space. Thanks for you input. – Jarzon Jan 24 '19 at 01:57
  • 1
    .input-hidden { opacity: 0; width: 0; height: 0; border: none; position: absolute; pointer-events: none; } // setting padding: 0; won't show required validation error. so don't set padding to 0; – Riajul Mar 06 '21 at 05:56
  • 1
    Is this the right solution though? Is there any accessiblity reasons to not do this? – dwjohnston May 26 '21 at 06:42
  • It's a bit better that other hacks to hide the upload input since you can still select the input with tab. But nothing will be highlighted to let you know it's selected. – Jarzon May 26 '21 at 21:49
3

But I think it's a nice approach and I also added

pointer-events: none;

to the input. So the user can't click on it and also the cursor doesn't change on hover.

10 Rep
  • 2,217
  • 7
  • 19
  • 33
DeadApe
  • 416
  • 1
  • 3
  • 10
0

This what have worked for me, you can't set the height to 0:

   input {
        opacity: 0;
        height: 1px;
        display: block
   }