16

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!

2
  • @Turing85 my question is how to let this field required
    – user9927491
    Commented Jun 18, 2018 at 20:34
  • input is hidden because of the property display: none. Moreover, do not use inline css. Commented Jun 18, 2018 at 20:40

3 Answers 3

25

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>

6
  • 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 Commented Jan 23, 2019 at 3: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
    Commented Jan 24, 2019 at 1:46
  • I added width: 0; so the input doesn't take width space. Thanks for you input.
    – Jarzon
    Commented Jan 24, 2019 at 1: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
    Commented Mar 6, 2021 at 5:56
  • 1
    Is this the right solution though? Is there any accessiblity reasons to not do this?
    – dwjohnston
    Commented May 26, 2021 at 6:42
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.

0

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

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

Your Answer

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