到目前为止,下面的代码没有更新ErrorMessages
常量的Email.value.Length
的值。 其思想是显示返回true的剩余字符数量;
预先感谢;
const email = document.getElementById("mce-EMAIL");
const errorMessages = {
typeMismatch: 'I am expecting an e-mail address!',
valueMissing: 'You need to enter an e-mail address',
tooShort: `Email should be at least ${ email.minLength } characters; you entered ${ email.value.length }`
};
function displayErrorMessage(errorMessage) {
return errorMessages[errorMessage];
}
const typeCheck = (onValue) => {
let typeMismatch, valueMissing, tooShort;
typeMismatch = (onValue.validity.typeMismatch) ? displayErrorMessage('typeMismatch') : true;
valueMissing = (onValue.validity.valueMissing) ? displayErrorMessage('valueMissing') : true;
tooShort = (onValue.validity.tooShort) ? displayErrorMessage('tooShort') : true;
return false;
}
email.addEventListener('input', (event) => {
typeCheck(event.explicitOriginalTarget);
});
如果您提供HTML,将更容易找到您所期望的内容。 ;o)
结果:您最初在函数中定义了常量ErrorMessages
。 这意味着它永远不会更新其中的值。
将常量放在DisplayErrorMessage()
函数中,它就会工作。
function displayErrorMessage(errorMessage) {
const errorMessages = {
typeMismatch: 'I am expecting an e-mail address!',
valueMissing: 'You need to enter an e-mail address',
tooShort: `Email should be at least ${ email.minLength } characters; you entered ${ email.value.length }`
};
return errorMessages[errorMessage];
}
下面是一个工作示例:
null
const email = document.getElementById("mce-EMAIL");
const output = document.getElementById("output");
function displayErrorMessage(errorMessage) {
const errorMessages = {
typeMismatch: 'I am expecting an e-mail address!',
valueMissing: 'You need to enter an e-mail address',
tooShort: `Email should be at least ${ email.minLength } characters; you entered ${ email.value.length }`
};
output.innerHTML = errorMessages[errorMessage];
return errorMessages[errorMessage];
}
const typeCheck = (onValue) => {
let typeMismatch, valueMissing, tooShort;
typeMismatch = (onValue.validity.typeMismatch) ? displayErrorMessage('typeMismatch') : true;
valueMissing = (onValue.validity.valueMissing) ? displayErrorMessage('valueMissing') : true;
tooShort = (onValue.validity.tooShort) ? displayErrorMessage('tooShort') : true;
return false;
}
email.addEventListener('input', (event) => {
typeCheck(event.explicitOriginalTarget);
});
<div class="container">
<input type="email" id="mce-EMAIL" minlength="10">
</div>
<div id="output"></div>