As a JavaScript beginner, I am currently exploring form validation and came across some code online that I find elegant and maintainable. However, my understanding of JavaScript is limited, so I need help deciphering the functions defined within the code.
I also want to implement an event-driven approach by calling the InstantValidation function when the form is submitted (onSubmit event) from a separate .js file using an event listener. Can someone guide me on how to properly call the function in this manner?
The provided code snippet is as follows:
<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">
// JavaScript code goes here
</script>
</body>
</html>
I am specifically looking for clarification on the following function:
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);
});
}
}
Any assistance in explaining this function would be greatly appreciated!