Jump to content
Larry Ullman's Book Forums

Validating Form Elements In Javascript


Recommended Posts

The following code is from chapter 5 of this book. 

 

if (!comments || !comments.value || (comments.value.indexOf('<') != -1) ){
okay = false;
alert ('Please enter your comments, without any HTML!');
 
My question is why do we have to both put !comments and also !comments.value. Aren't they the same?? Why check comments if it doesn't have a value. I just learned php with Larry's book, and am new at javascript. 
Link to comment
Share on other sites

Basically, you never want to assume anything in programming.

In this case, you're ensuring that comments is not null (i.e., it's a valid DOM element) and that it has the value property (i.e., it's a valid form input element).

 

If you assume both of those things without checking, then your code would through an error on the comments.value.indexOf part of the if statement whenever comments was not set to a DOM input element.

 

That make sense?

Link to comment
Share on other sites

 Share

×
×
  • Create New...