jquery - 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!
解决方案
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("");
}
}
推荐阅读
- javascript - 使用 setAttribute() 将 onkeyup 函数添加到函数中带有文本参数的 DOM 元素
- c++ - 如何在模板中转发通用结构的初始化参数?
- c - 根据 C 标准,int 的大小是多少?
- c++ - Why is my struct constructor, which contains other structs, not working?
- python - 关于 python 上 sort() 方法的一些问题
- javascript - mongoose find() 方法不是服务调用中的函数错误
- list - 在 Flutter 中调用函数时遇到空引用问题
- mysql - MYSQL 将毫秒转换为仅 MM:SS
- c# - 手动调整位图大小
- python - 无法加载 CSS Django IIS