Skip to main content

Input file validation with alert using javascript.

 Following code validates the file extension as soon as file is selected. If the extension/s are not as per requirement this will reset the input box with alert.

//Javascript code -- add following code into html head.

    <script>
       var _validFileExtensions = [".jpg", ".jpeg", ".bmp", ".gif", ".png"];   
        function ValidateSingleInput(oInput) {
            if (oInput.type == "file") {
                var sFileName = oInput.value;
                 if (sFileName.length > 0) {
                    var blnValid = false;
                    for (var j = 0; j < _validFileExtensions.length; j++) {
                        var sCurExtension = _validFileExtensions[j];
                        if (sFileName.substr(sFileName.length - sCurExtension.length, sCurExtension.length).toLowerCase() == sCurExtension.toLowerCase()) {
                            blnValid = true;
                            break;
                        }
                    }
                    
                    if (!blnValid) {
                        alert("Invalid file. Only image files are allowed. (.jpg .jpeg .bmp .gif .png)");
                        oInput.value = "";
                        return false;
                    }
                }
            }
            return true;
        }
    </script>


// HTML input file code

    <input type="file" onchange="ValidateSingleInput(this);" name="avatarUrl"/>

Comments

Popular posts from this blog

Simple method to connect database using PHP.

    $servername = "localhost"; $username = "root"; $password = ""; $dbname = "jjmtmain"; // Create connection $conn = mysqli_connect($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) {     die("Connection failed: " . $conn->connect_error); } else {     echo "Connected to database."; }  /* In further operations you can use the $conn object for the database connection.              For eg. $q = mysqli_query($conn, "select * from user where email='$userid'"); $r = mysqli_fetch_array($q); echo $name = $r['name']; */

PHP INI & ON PAGE ERROR REPORTING

  Enable-Disable on-page error reporting for debugging purpose.   //Turn off error reporting error_reporting(0); //Report runtime errors error_reporting(E_ERROR | E_WARNING | E_PARSE); //Report all errors error_reporting(E_ALL); //Same as error_reporting(E_ALL); ini_set("error_reporting", E_ALL); //Report all errors except E_NOTICE error_reporting(E_ALL & ~E_NOTICE); // Removing memory limit ini_set("memory_limit",-1); //Removing max execution time for php ini_set('max_execution_time', 0);