简体   繁体   English

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

[英]Required field only if condition is met

I have a form with, among other fields, a picture for the user to upload and a hidden field to hold ID. 除其他字段外,我还有一个表格,其中有一张供用户上传的图片和一个包含ID的隐藏字段。 I need the picture to be required only if ID is empty, otherwise the user is editing, so there is already a picture in there. 我仅在ID为空时才需要图片,否则用户正在编辑,因此那里已经有图片。

Can it be done with HTML only? 只能用HTML完成吗? Maybe this could be done with javascript, but how to show this default popup (shown below) that appears when you just set required ? 也许可以用javascript来完成,但是如何显示刚设置为required时出现的默认弹出窗口(如下所示)? I've checked this and this questions, but they don't provide the expected result. 我已经检查了这个这个问题,但是它们没有提供预期的结果。

Popup: 弹出:

Any ideas? 有任何想法吗?

To set that 'popup', you need to call HTMLSelectElement.setCustomValidity() on the element. 要设置该“弹出窗口”,您需要在该元素上调用HTMLSelectElement.setCustomValidity()

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

The code found here helped me figure it out. 这里找到的代码帮助我弄清楚了。

Simple: Consider to use an array called "files" of your images ID´s: 简单:考虑使用图像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.
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM