long.luc
long.luc

Reputation: 1191

Resetting form removes HTML 5 validation on input file

I have encountered this problem and still have no clue/idea about this.

This is my code:

<form onsubmit="return false;">
    <input type="file" required />
    <br/>
    <button type="reset">Reset</button>
    <button type="submit">Upload</button>
</form>

As you can see, clicking "Upload" will trigger HTML validation on file input and a error message will be shown.

But if I select a file then click "Reset" button to reset the form. After that, I click "Upload" (submit form), the validation is gone.

I also tries using javascript method reset() but the problem still remained.

Note that I use Google Chrome browser.

Does anyone have some ideas about this issue?

Or have I just encountered a bug of HTML validation?

Upvotes: 2

Views: 769

Answers (2)

Chi Row
Chi Row

Reputation: 1106

It looks like it's a bug with Chrome.
You can see the difference by adding the below CSS on input field.

input:invalid {
    color: blue;
} 

When you reset on FF, the input field becomes invalid but on Chrome, it does not. On Chrome, if you select a file and then bring up the select screen again then cancel it, the field becomes invalid. That seems like the only way to reset the input field.

Looks like you will have to add some code.

Upvotes: 2

Danny
Danny

Reputation: 7518

Only browser I had problems with this was on Chrome. The below would fix the issue for me (not sure why it works)

$("button[type='reset']").on('click', function() {
    $("#file").replaceWith('<input id="file" type="file" required />');
    return true;
});

JSFiddle

Upvotes: 0

Related Questions