I am trying to create a basic unobtrusive form validation function but I am having some issues/questions. Basically I am checking if any of the form fields have <= 3 characters, and if they do so, then I make those fields' backgrounds and borders red. Also in the empty <span> tags I insert an error message. My issues/questions are:
#1: So when I say if (fieldVals[i]<=3) this means that the errors should appear if the values are 1,2 or 3 characters long, right? It does not do that though, when I insert one character in any of the form fields the errors go away, but they should not, right?
#2: How do I cancel the form from submitting if errors are visible and vice versa? When I use the return false when errors are visible, the code does not even run. What is going on? return true does the same.
#3: When I use a submit button(type="submit") instead of just a button(type="button"), the code does not run? What am I doing wrong?
NOTE: I am not trying to use this on a website, I am just trying to learn how to use unobtrusive javascript. That's why I am only checking for empty fields. If I learn how to do this first, later I will try to add email check, date check etc.
(sorry for the long message)
Any help would be much appreciated, thanks!
THE CODE:
function addEvent (eventObj, event, codeToEexcute) {
if (eventObj.addEventListener) { eventObj.addEventListener(event, codeToEexcute, false );
}
else if (eventObj.attachEvent) { // If IE
event = "on" + event; eventObj.attachEvent(event, codeToEexcute);
}
}
function cancelEvent(event) {
if (event.preventDefault) {
event.preventDefault();
event.stopPropagation();
}
else {
event.returnValue = false;
event.cancelBubble = true;
}
}
addEvent(window, 'load', pageEvents);
function pageEvents () {
if (!document.getElementById || !document.createTextNode) {return;}
var send = document.getElementById('send');//<input type="button" id="send" value="Contact Us" />
if (!send) {return;}
addEvent(send, 'click', validate);
}
function validate () {
var name = document.getElementById('name'); //<input type="text" name="name" id="name" value="" />
var lastName = document.getElementById('lastName'); //<input type="text" name="lastName" id="lastName" value="" />
var email = document.getElementById('email'); //<input type="text" name="email" id="email" value="" />
var subject = document.getElementById('subject'); //<input type="text" name="subject" id="subject" value="" />
var message = document.getElementById('message'); //<textarea name="message" id="message" value=""></textarea>
var fields = [name, lastName, email, subject, message];
var fieldVals = [name.value, lastName.value, email.value, subject.value, message.value];
for (var i = 0; i<fieldVals.length; i++) {
var contactForm = document.getElementById('contactForm'); //<form> tag
var errs = contactForm.getElementsByTagName('span'); //one empty <span> tag next to each form field
if (fieldVals[i]<=3) { //BUG HERE: it still validates with 3 or less character but it should not, right?
fields[i].style.background = "#FFCCCC";
fields[i].style.borderColor = "red";
errs[i].innerHTML ="Please enter a correct value"; //by using 'i' I get the same index for the <span> tags //if I insert a "return false" here, the code above does not run. //how do I make the form not to submit when the code above is executed?
}
else {
fields[i].style.background = "none";
fields[i].style.borderColor = "#cecece";
errs[i].innerHTML = " "; //how do I make the form to submit? when i use "return true" the code above does not run.
}
}//end for loop
}//end validate
What if the user enters three spaces or ??? into the field?
var send = document.getElementById('send')
var name = document.getElementById('name');
var subject = document.getElementById('subject');
It is advised that you do not use exactly the same name for a JavaScript variable and an HTML element. This will cause the script to fail in IE if you omit the var keyword (i.e. give the variable global scope).
Thank you for pointing out that IE will give an error if global variables have the same name as HTML elements (I did not know that). In terms of what happens if the user enters three spaces - if the user enters three spaces, the validation will fail because I am testing for less than or three. But your logic is correct. If the user enters four spaces our four characters such as "****", then the validation will pass. Perhaps there are Regular Expressions for matching white spaces and other characters (I will look into it). Thank you for point them out, I appreciate it.
It was silly of me to forget the length property, thank you for catching that. The boolean flag method is awesome and it makes sense. I added the return validate() on the form tag and it works fine. The thing is that I am trying to validate through only JS code and did not want to have to go into the form tag and add an onsubmit event-handler, although it works fine. I think there is a way of validating through only JS code, but I am not sure how. I tried to use my addEven() like this instead:
var contactForm = document.getElementById('contactForm');
addEvent(contactForm, 'submit', validate);
It did not work though... And when I tried to add this:
var contactForm = document.getElementById('contactForm');
addEvent(contactForm, 'submit', return validate);
It gave me a syntax error. I will look more into it, but if you have any suggestions, please let me know. Thank you for your help!
x = x.replace(/^\s+|\s+$/g,""); // strip leading and trailing spaces
x = x.replace(/[^a-z\s\-\']/gi,""); strip anything except letters spaces hyphen apostrophe (name can be Riley-O'Flanagan).
Thank you for that, it will be very useful.
My validation is almost ready, but I encountered another issue. This is what happens: When I leave everything empty the errors appear (great!), when I fill in all values except some values of text boxes, the errors for those text boxes appear just fine (great!), but when I leave all the text boxes empty and I only fill in the textarea(var message), the form validates anyway. I think it has do with the array fields[i] and the fact that arrays start with 0. I am not sure how to add 1 to the array and at the same time test it. I tried something like this but no luck:
var valid = true;
var emptyFields = fieldVals[i].length<=3;
if (emptyFields) {
(fields[i] +1).style.background="#FFCCCC";
(fields[i] +1).style.borderColor = "red";
errs[i].innerHTML = "Please enter a correct value";
valid = false;
}
Unfortunately it did not work , as soon as I press the submit button it validates and it does not display any errors. I am not sure why that happens . I guess JS is really kicking me in the head! Any other suggestions would be much appreciated!