1

I have just started with web programming. I need to validate and upload a file. and I make 2 conditions when the file type doesnt match then show a alert ("Invalid file") and second condition, when the file is empty or match then data inserted. but when file/image type is empty, data cannot be inserted. this My HTML code is basically as below :

<form method="post" id="insert_form" enctype="multipart/form-data">
  <label>Enter Employee Name</label>
  <input type="text" name="name" id="name" class="form-control" />
  <br />
  <label>Enter Employee Address</label>
  <textarea name="address" id="address" class="form-control"></textarea>
  <br />
  <label>Select Gender</label>
  <select name="gender" id="gender" class="form-control">
    <option value="Male">Male</option>
    <option value="Female">Female</option>
  </select>
  <br />
  <label>Enter Designation</label>
  <input type="text" name="designation" id="designation" class="form-control" />
  <br />
  <label>Enter Age</label>
  <input type="text" name="age" id="age" class="form-control" />
  <br />
  <label>File</label>
  <br>
  <div>
    <img src="" id="pict" width="100px" class="img-thumbna">
  </div>
  <br>
  <input type="file" name="image" id="image">
  <br/>
  <input type="hidden" name="employee_id" id="employee_id" />
  <input type="submit" name="insert" id="insert" value="Insert" class="btn btn-success" />
</form>

my Validation code :

function listMajors(auth) {
  const sheets = google.sheets({ version: 'v4', auth });
  sheets.spreadsheets.values.get({
    spreadsheetId: '1S5SDKN0t7jsiL_7LVPdpDWWay1_0Bv5LOAO9EaTw_8M',
    range: 'Sheet1!A:A',
  }, (err, { data }) => {
    if (err) return console.log('The API returned an error: ' + err);
    const rows = data.values;
    if (rows.length) {
      // console.log('Name, Major:');
      // Print columns A and E, which correspond to indices 0 and 4.
      rows.map((row) => {
        // console.log(`${row[0]}, ${row[4]}`);
      })
    } else {
      console.log('No data found.');
    }
  });
}

$("#insert_form").on('submit', function (event) {
  event.preventDefault();
  var exten = $("#image").val().split('.').pop().toLowerCase();

  if ($("#name").val() == "") {
    alert('name is required');
  }
  else if (jQuery.inArray(exten, ['jpg', 'jpeg']) == -1) {
    alert("Invalid File");
  }
  else {
    $.ajax({
      url: 'insert.php',
      method: 'POST',
      data: new FormData(this),
      contentType: false,
      processData: false,

      beforeSend: function () {
        $("#insert").val('Inserting....');
      },
      success: function (data) {
        $("#add_data_Modal").modal('hide');
        $("#insert_form")[0].reset();
        $("#employee_table").html(data);
      }
    });

  }
});

could you please help me with this

2
  • 2
    Since you say you're new to web, I want to be sure you are aware: Make sure that your client side validation (JavaScript/JQuery) is only for UI purposes. You should never trust client side code, as it can be modified or completely skipped. Even with validation in JavaScript, an attacker can bypass it and send a dangerous file to your server. You will need to have validation on the server side as well. Commented May 1, 2018 at 2:41
  • oke thank you...very helpful for the next step Commented May 1, 2018 at 4:04

2 Answers 2

1

this.files is an array within the selected file(s).

this.files[0].type.split('/')[1] get the type of the file and split the string with /. The type of the file would be like image/jpg, image/png, text/plain, etc.

So you can check if the type is in the valid extension array.

Here's a simple demo.

let validExt = ['jpg', 'jpeg']

$('input').on('change', function(){
  var extension = this.files[0].type.split('/')[1]
  console.log(this.files[0].type)
  if(validExt.indexOf(extension) == -1){
    alert('Invalid file.')
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file">

Sign up to request clarification or add additional context in comments.

Comments

1

You need to make little change in your script

$("#insert_form").on('submit', function (event) {
    event.preventDefault();
    formData = new FormData($(this)[0]);//This will contain your form data
    var exten = $("#image").val().split('.').pop().toLowerCase();
    if ($("#name").val() == "") {
        alert('name is required');
    }
    else if (jQuery.inArray(exten, ['jpg', 'jpeg']) == -1) {
        alert("Invalid File");
    }
    else {
        $.ajax({
            url: 'insert.php',
            method: 'POST',
            data: formData,
            cache: false,// add this line too
            contentType: false,
            processData: false,
            beforeSend: function () {
                $("#insert").val('Inserting....');
            },
            success: function (data) {
                $("#add_data_Modal").modal('hide');
                $("#insert_form")[0].reset();
                $("#employee_table").html(data);
            }
        });
    }
});

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.