I am writing a custom form validation script compatible with IE8+. I just wanted to make sure I am not messing anything up. I have tested on IE8 its works. However, I want to make sure I am doing it the right way.
var wrapper = document.querySelector('.wrapper');
var btn = document.querySelector('button');
var inputs = document.querySelectorAll('input');
// var required = document.querySelectorAll('input');
var textarea = document.querySelector('textarea');
// var ajaxRequest = new XMLHttpRequest();
function validateForm(e) {
var dataString = '';
e.preventDefault ? e.preventDefault() : e.returnValue = false;
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].addEventListener) {
inputs[i].addEventListener('blur', validateForm);
} else if (inputs[i].attachEvent) {
inputs[i].attachEvent('onblur', validateForm);
}
var value = inputs[i].value;
if (value === '' || value === 'Required') {
inputs[i].parentNode.setAttribute('class', 'error');
// return false;
} else {
inputs[i].parentNode.setAttribute('class', 'success');
}
}
if (textarea.value === '' || textarea.value === 'Required') {
textarea.value = 'Required';
}
for (var i = 0; i < inputs.length; i++) {
dataString += inputs[i].name + '=' + inputs[i].value + '&';
}
dataString += textarea.name + '=' + textarea.value;
// ajaxRequest.open('GET', 'email.php?' + dataString, false);
// ajaxRequest.send(null);
// var response = ajaxRequest.responseText;
// if (response === '') {
// wrapper.innerHTML = '';
// wrapper.innerHTML = '<h2>Comment received!</h2>';
// }
}
if (btn.addEventListener) {
btn.addEventListener('click', validateForm, false);
} else if (btn.attachEvent) {
btn.attachEvent('onclick', validateForm);
}
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Form Validate</title>
<style>
p.error input {
border: 2px solid red;
}
p.success input {
border: 2px solid green;
}
</style>
</head>
<body>
<div class="wrapper">
<form id="form" method="get" action="test.php">
<p>
<label for="name">Name:</label>
<input class="required" type="text" name="name">
</p>
<p>
<label for="email">Email:</label>
<input class="required" type="email" name="email">
</p>
<p>
<label for="company">Company:</label>
<input type="text" name="company">
</p>
<p>
<label for="comments">Comments:</label>
<textarea name="comments"></textarea>
</p>
<p>
<button type="submit">Submit</button>
</p>
</form>
</div>
</body>
</html>