仅当条件满足时为必填字段

Required field only if condition is met

我有一个表单,在其他字段中,有一张供用户上传的图片和一个用于保存 ID 的隐藏字段。我需要图片只有在ID为空的情况下才需要,否则用户正在编辑,所以里面已经有图片了。

只用HTML可以吗?也许这可以用 javascript 来完成,但是如何显示刚刚设置 required 时出现的默认弹出窗口(如下所示)?我检查了 this and this 个问题,但它们没有提供预期的结果。

弹出窗口:

有什么想法吗?

简单: 考虑使用名为 "files" 的图像 ID 数组:

var file = this.files[0];
var fileType = file["type"];
var ValidImageTypes = ["image/gif", "image/jpeg", "image/png"];
if ($.inArray(fileType, ValidImageTypes) < 0) {
     // invalid condition goes here.
}

要设置 'popup',您需要对该元素调用 HTMLSelectElement.setCustomValidity()

var foo = document.getElementById("foo");
// check condition
foo.setCustomValidity("A custom message for the popup");

找到的代码 here 帮我弄明白了。