JSFiddle - React, Tailwind, and code Playground

by Barney Carroll

HTML

<form type="POST">
    <input required="required" type="file" accept="image/*" />
    <button type="submit">Submit</button>
</form>

JavaScript

void function enhanceFileInputTypeValidityCheck(){
    var inputPrototype      = document.createElement( 'input' ).constructor.prototype;
    var nativeCheckValidity = inputPrototype.checkValidity;

    function validateFileInputType( input ){
        var MIMEtype = new RegExp( input.accept.replace( '*', '.\*' ) );

        return Array.prototype.every.call( input.files, function passesAcceptedFormat( file ){
            return MIMEtype.test( file.type );
        } );
    }

    inputPrototype.checkValidity = function enhancedCheckValidity(){
        if( this.type === 'file' &&  this.accept && this.files && this.files.length ){
            if( !validateFileInputType( this ) ){
                console.log( 'Custom validation: fail' );
                
                this.setCustomValidity( 'Please only submit files of type ' + this.accept );
                
                return false;
            }
            else {
                console.log( 'Custom validation: pass' );
            }
        }

        return nativeCheckValidity.apply( this );
    }
}();

$( 'input' ).on( 'input', function( event ){
    console.log( event );
    
    this.checkValidity();
} );