具有3个参数的JS验证函数(//选择器、消息、特定输入的验证函数)



我需要实现代码,该代码应该添加eventlistener,并在更改事件时检查表单是否有效,并添加消息

let validate = function(element, info, functionValidate) {

let htmlTag = document.querySelector('fieldElem');//?
htmlTag.addEventListener('change',ev=>{
let notif = document.createElement('span');
document.htmlTag.appendChild(notif);//should add span element next to input
if(fieldElem.value == '')
{
notif.style.visibility = "hidden"; //hide span if nothing happens
}
//I need to implement code which should add eventlistener and on change event check if the form is valid and add the message...

尝试以下操作。您也可以使用表单验证(例如,请参阅表单验证集自定义有效性(

function validator(val) {
return (val != '');
}
function validateField(element, validator, message) {
var helper = document.createElement("span");
var parent = element.parentElement;
parent.appendChild(helper);


element.addEventListener('change', function() {
var val = element.value;
if (!validator(val)) {
helper.innerText = message;
} else {
helper.innerText = "";
}
});
}
validateField(document.getElementById('test'), validator, 'Wrong input');
<html>
<body>
<form>
<input id="test" type="text" placeholder="Type here"/>
</form>
</body>
</html>

最新更新