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 post
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 post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...