【问题标题】:Validate and Post file using Jquery, PHP使用 Jquery、PHP 验证和发布文件
【发布时间】:2021-11-11 20:48:48
【问题描述】:

我正在开发一个小项目,我目前正在尝试在 php 中使用 JQuery 验证注册表单。问题是我无法找出图像格式的正确正则表达式。验证函数:

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

我还有其他字段,如姓名、姓氏等,但它们工作得很好,这就是为什么不包括在内。请帮忙!

【问题讨论】:

    标签: jquery validation file-upload frontend


    【解决方案1】:

    问题出在测试函数中使用的变量“photo”,要解决你需要创建一个变量来获取文件名并使用Regex表达式进行验证,例如:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-20
      • 2017-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-11
      相关资源
      最近更新 更多