gpt4 book ai didi

JavaScript 表单验证 : understanding function call

转载 作者:搜寻专家 更新时间:2023-11-01 04:17:45 24 4
gpt4 key购买 nike

我是 JavaScript 的新手,正在努力寻找表单验证的方法。我一直在阅读书籍和在线教程,我在网上找到了以下代码,在我看来,它非常优雅且易于维护。不幸的是,我的 JavaScript 技能还不足以理解所有内容。我在这里请求您的帮助,以了解定义的不同功能。

我还想在一个事件(onSubmit 事件)上调用 InstantValidation 函数,在一个独立的 .js 文件(基于事件监听器)中调用它,所以你能不能也帮我适本地调用这个函数?

这是代码:

<html>

<body>

<form id="myform" action="#" method="get">
<fieldset>

<legend><strong>Add your comment</strong></legend>

<p>
<label for="author">Name <abbr title="Required">*</abbr></label>
<input name="author" id="author" value=""
required="required" aria-required="true"
pattern="^([- \w\d\u00c0-\u024f]+)$"
title="Your name (no special characters, diacritics are okay)"
type="text" spellcheck="false" size="20" />
</p>

<p>
<label for="email">Email <abbr title="Required">*</abbr></label>
<input name="email" id="email" value=""
required="required" aria-required="true"
pattern="^(([-\w\d]+)(\.[-\w\d]+)*@([-\w\d]+)(\.[-\w\d]+)*(\.([a-zA-Z]{2,5}|[\d]{1,3})){1,2})$"
title="Your email address"
type="email" spellcheck="false" size="30" />
</p>

<p>
<label for="website">Website</label>
<input name="website" id="website" value=""
pattern="^(http[s]?:\/\/)?([-\w\d]+)(\.[-\w\d]+)*(\.([a-zA-Z]{2,5}|[\d]{1,3})){1,2}(\/([-~%\.\(\)\w\d]*\/*)*(#[-\w\d]+)?)?$"
title="Your website address"
type="url" spellcheck="false" size="30" />
</p>

<p>
<label for="text">Comment <abbr title="Required">*</abbr></label>
<textarea name="text" id="text"
required="required" aria-required="true"
title="Your comment"
spellcheck="true" cols="40" rows="10"></textarea>

</p>

</fieldset>
<fieldset>

<button name="preview" type="submit">Preview</button>
<button name="save" type="submit">Submit Comment</button>

</fieldset>

</form>



<script type="text/javascript">
(function()
{

//add event construct for modern browsers or IE
//which fires the callback with a pre-converted target reference
function addEvent(node, type, callback)
{
if(node.addEventListener)
{
node.addEventListener(type, function(e)
{
callback(e, e.target);

}, false);
}
else if(node.attachEvent)
{
node.attachEvent('on' + type, function(e)
{
callback(e, e.srcElement);
});
}
}


//identify whether a field should be validated
//ie. true if the field is neither readonly nor disabled,
//and has either "pattern", "required" or "aria-invalid"
function shouldBeValidated(field)
{
return (
!(field.getAttribute('readonly') || field.readonly)
&&
!(field.getAttribute('disabled') || field.disabled)
&&
(
field.getAttribute('pattern')
||
field.getAttribute('required')
)
);
}


//field testing and validation function
function instantValidation(field)
{
//if the field should be validated
if(shouldBeValidated(field))
{
//the field is invalid if:
//it's required but the value is empty
//it has a pattern but the (non-empty) value doesn't pass
var invalid =
(
(field.getAttribute('required') && !field.value)
||
(
field.getAttribute('pattern')
&&
field.value
&&
!new RegExp(field.getAttribute('pattern')).test(field.value)
)
);

//add or remove the attribute is indicated by
//the invalid flag and the current attribute state
if(!invalid && field.getAttribute('aria-invalid'))
{
field.removeAttribute('aria-invalid');
}
else if(invalid && !field.getAttribute('aria-invalid'))
{
field.setAttribute('aria-invalid', 'true');
}
}
}


//now bind a delegated change event
//== THIS FAILS IN INTERNET EXPLORER <= 8 ==//
//addEvent(document, 'change', function(e, target)
//{
// instantValidation(target);
//});


//now bind a change event to each applicable for field
var fields = [
document.getElementsByTagName('input'),
document.getElementsByTagName('textarea')
];
for(var a = fields.length, i = 0; i < a; i ++)
{
for(var b = fields[i].length, j = 0; j < b; j ++)
{
addEvent(fields[i][j], 'change', function(e, target)
{
instantValidation(target);
});
}
}


})();
</script>

</body>
</html>

特别是,以下代码对我来说不是很清楚:

    function addEvent(node, type, callback)
{
if(node.addEventListener)
{
node.addEventListener(type, function(e)
{
callback(e, e.target);

}, false);
}
else if(node.attachEvent)
{
node.attachEvent('on' + type, function(e)
{
callback(e, e.srcElement);
});
}
}

任何帮助(即使是非常简短的解释)将不胜感激!

最佳答案

#1 这是事件处理程序抽象层。

一个代码部分充当事件处理程序,但适用于各种不同的浏览器。

该函数允许使用两种方式。

它让你通过...

  • ...您要向其添加事件的元素(节点)
  • ...您想处理什么类型的事件(type)
  • ...您希望事件执行什么代码(回调)

浏览器事件: http://eloquentjavascript.net/chapter13.html

抽象层: http://en.wikipedia.org/wiki/Abstraction_layer

浏览器事件是诸如页面完全加载 (onload)、某项被点击 (onclick)、输入被更改 (onchange) 之类的事件), 光标在元素上移动 (onmouseover), 等等...

http://www.w3schools.com/js/js_htmldom_events.asp

#2 如何调用验证onSubmit...

//now bind a change event to each applicable for field

下面的代码遍历每个 inputtextarea 元素,并使用 onchange 事件为每个元素添加验证。但是你想要做的是验证 onsubmit,这需要类似这样的东西,在另一个 addEvent 调用下面:

addEvent("myform","onsubmit", function(){
//de Go field by field and validate.
//de If all the fields pass, return true.
//de If one or more fields fail, return false.
})

如果需要,您甚至可以删除 onChange 事件。那是你的选择。这里的主要事情是您需要确保只验证表单本身内的字段,您可以查看此答案以获取有关以下内容的更多信息:Best Practice: Access form elements by HTML id or name attribute? ...循环遍历所有元素,并验证我上面提到的 addEvent 中的每个元素,它必须返回 truefalse 以允许要提交的表单,或停止提交并显示存在验证错误。

请记住!作为个人建议...在服务器端您仍然想要进行验证,即使您有客户端验证。浏览器很容易操作,所以您可能仍然有错误的数据发送到服务器。无论客户端如何,总是,总是进行服务器端验证。

关于JavaScript 表单验证 : understanding function call,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21022258/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com