有没有办法更改默认表单验证消息的区域设置,以便无论浏览器的语言如何,它们始终以英语显示。
我不想通过 setCustomValidity 设置自定义消息,我想使用浏览器的消息,但我希望它们始终为英文。
显示预期用途的代码示例:
[...e.currentTarget.elements].reduce((acc, el) => {
if (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement)
if (el.validationMessage)
return { ...acc, [el.name]: el.validationMessage };
return acc;
}, {})
我并不是 100% 清楚您希望无效消息是什么样子。这里有两种不同的形式。第一个使用 setCustomValidity() 方法,另一个具有自定义设置,其中浏览器消息不显示,但在 HTML 中显示消息。
document.forms.form01.addEventListener('invalid', e => {
e.target.setCustomValidity("This is the custom message");
}, true);
document.forms.form02.addEventListener('invalid', e => {
e.preventDefault();
e.target.classList.add('invalid');
}, true);
document.forms.form02.addEventListener('input', e => {
if (e.target.validity.valid) {
e.target.classList.remove('invalid');
}
}, true);
input~span {
display: none;
}
input.invalid~span {
display: inline;
}
<form name="form01">
<input type="text" required>
<button>Submit</button>
</form>
<form name="form02">
<input type="text" required>
<span>This is the custom message</span>
<button>Submit</button>
</form>