Home > other >  Validate and Post file using Jquery, PHP
Validate and Post file using Jquery, PHP

Time:09-17

I am developing a small project and I am currently trying to validate Register Form with JQuery in php. The problem is that I cant figure out the right regex for the image format. Validate function:

function validateRegisterForm(event) {
event.preventDefault();
var photo=$("#profphoto")[0].files; 
var photo_pattern = /\.(?:jpeg|jpg|gif)$/
    if (!photo_pattern.test(photo)) {
        if (isEmpty(photo)) {
            $("#error_photo").text("Photo can not be empty");
            $("#profphoto").focus();
            return;
        }else{
            $("#error_photo").text("Upload format is not correct");
            $( "#profphoto" ).focus();
            return;
        }
    }else {
        $("#error_photo").text("");
    }
}

I have also other fields like name, lastname ect but they work just fine and thats why they are not included. A little help please!

CodePudding user response:

The issue is in the variable "photo" used in the test function, to solved you need to create a variable to get the filename and use to validate with the Regex expression, for example:

function validateRegisterForm(event) {
    event.preventDefault();
    var photo=$("#profphoto")[0].files;
    var filename=photo[0]?.name; 
    var photo_pattern = /\.(?:jpeg|jpg|gif)$/

    if (!photo_pattern.test(filename)) {
        if (isEmpty(photo)) {
            $("#error_photo").text("Photo can not be empty");
            $("#profphoto").focus();
            return;
        }else{
            $("#error_photo").text("Upload format is not correct");
            $( "#profphoto" ).focus();
            return;
        }
    }else {
        $("#error_photo").text("");
    }
}
  • Related