首页 > 解决方案 > Validate and Post file using Jquery, PHP

问题描述

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!

标签: jqueryvalidationfile-uploadfrontend

解决方案


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("");
    }
}

推荐阅读