drago354
drago354

Reputation: 79

ColdFusion CFIF

I am new to ColdFusion. I'm trying to do some form field validation. However, my CFIF's don't seem to be working if the form.name and form.address fields are empty.

Here is my code:

         <cfif IsDefined("form.name")>
           <cfif IsDefined("form.address")>
              Your shipping address is:<br>
              <cfoutput>
                 #form.name#<br>
                 #form.address#<br>
                 #form.state#<br>
                 #form.shipping#<br>
                 #form.brochure#<br>
              </cfoutput>

           <cfelse>
              You did not enter an address.
           </cfif>   
         <cfelse>
              You did not enter a name.
         </cfif>  

Upvotes: 2

Views: 471

Answers (4)

Andy
Andy

Reputation: 169

I would think that if your are submitting a form set that the fields must exist so checking to see if they are there is unnecessary.

 <cfif (form.name IS "")  OR (form.address IS "")>
   We need your name and address to ship your item(s).
 <cfelse>
   Your shipping address is:<br>
          <cfoutput>
             #form.name#<br>
             #form.address#<br>
             #form.state#<br>
             #form.shipping#<br>
             #form.brochure#<br>
          </cfoutput>
  </cfif>

Minor issue but i never have used the form. part of a variable except in database writes.

Upvotes: 0

Carl Von Stetten
Carl Von Stetten

Reputation: 1149

You are only checking if the fields exist. Text input fields will always exist in the submitted form variables, even if they are empty. You need to also check if the field values aren't empty strings. Additionally, you should consider using StructKeyExists() instead of IsDefined() as it is more precise and in some cases performs better. So you could try:

<cfif StructKeyExists(form, "name") AND Len(Trim(form.name))>

This will check if the "name" form field arrived in the FORM scope, and that the value in that variable is at least one character other than a space.

Upvotes: 15

Craig Verrastro
Craig Verrastro

Reputation: 51

An similar alternative to Carl's answer is

<cfif StructKeyExists(form, "name") AND Trim(form.name) NEQ ''>

Upvotes: 0

Dsmithdallas
Dsmithdallas

Reputation: 31

You may also consider checking for blank fields or missing input using Javascript or jQuery, notifying the user before they leave the page is considered courteous.

Upvotes: 0

Related Questions