Javascript Reference - HTML DOM Input FileUpload required Property








The required property sets or gets whether a file must be selected before submitting a form.

Browser Support

required Yes 10.0 Yes Yes Yes

Syntax

Return the required property.

var v = fileuploadObject.required 

Set the required property.

fileuploadObject.required=true|false

Property Values

Value Description
true|false Set whether a file upload field is required for a form.
  • true - The file upload field is required
  • false - Default. The file upload field is not required




Return Value

A Boolean type value, true if the file upload field is a required part of form submission, otherwise false.

Example

The following code shows how to set a file upload field to be required.


<!DOCTYPE html>
<html>
<body>
<!--   w ww  .  j  a  va  2  s  .  com-->
<form action="url">
  Select a file: <input type="file" id="myFile" name="usr_file">
  <input type="submit">
</form>
<button onclick="myFunction()">test</button>
<p id="demo"></p>

<script>
function myFunction() {
    document.getElementById("myFile").required = true;
    document.getElementById("demo").innerHTML = "changed";
}
</script>

</body>
</html>

The code above is rendered as follows:





Example 2

The following code shows how to check if a file must be selected before submitting a form.


<!DOCTYPE html>
<html>
<body>
<!--from  w  ww .j  a va  2s. co m-->
<form action="url">
  Select a file: <input type="file" id="myFile" name="usr_file" required>
  <input type="submit">
</form>
<button onclick="myFunction()">test</button>

<p id="demo"></p>

<script>
function myFunction() {
    var x = document.getElementById("myFile").required;
    document.getElementById("demo").innerHTML = x;
}
</script>

</body>
</html>

The code above is rendered as follows: