?
Solved

Check form first and provoke warning if form field is blank

Posted on 2003-03-31
21
Medium Priority
?
159 Views
Last Modified: 2013-12-24
Hello, I would like to know how to validate a form first to see if someone chose a image file to upload.  I am not using <CFFORM>.  So I would like to make sure that a person chooses a file to upload.  When the user hits submit I want it to alert them that a file was not selected.  Does anyone have a simple process for this without using <CFFORM>

Thank you,
Jeff
0
Comment
Question by:jeffmace
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 7
  • 6
  • 3
  • +3
21 Comments
 
LVL 8

Expert Comment

by:TallerMike
ID: 8241038
function hasValue(inputObj)
  { return (inputObj.length > 0); }

function validateForm(formObj)
  {
  if (!hasValue(formObj.fieldName)
    {
    alert("You must enter a file name");
    return fasle;
    }
  else
    { return true; }
  }


Then on your form:

<form onsubmit="return validateForm(this)">
0
 
LVL 8

Expert Comment

by:TallerMike
ID: 8241046
in the validateForm function, you'll want to list through the inputs that are required, something like so:

function validateForm(formObj)
 {
 if (!hasValue(formObj.fname)
   {
   alert("You must enter your first name");
   return false;
   }
 else if (!hasValue(formObj.lname)
   {
   alert("You must enter your last name");
   return false;
   }
 else if (!hasValue(formObj.fileInput)
   {
   alert("You must enter file to load");
   return false;
   }
 else
   { return true; }
 }
0
 
LVL 8

Expert Comment

by:TallerMike
ID: 8241055
Oops, make sure of 2 things:

You spell false correctly, and that you add a parentheses on the if portion like so:

 else if (!hasValue(formObj.lname))

I forgot one on each of the if/else if statements
0
Learn how to optimize MySQL for your business need

With the increasing importance of apps & networks in both business & personal interconnections, perfor. has become one of the key metrics of successful communication. This ebook is a hands-on business-case-driven guide to understanding MySQL query parameter tuning & database perf

 

Author Comment

by:jeffmace
ID: 8241124
Here is what I have in the head of my page:

<script language="JavaScript" type="text/JavaScript">
function hasValue(inputObj)
 { return (inputObj.length > 0); }

function validateForm(formObj)
 {
 if (!hasValue(formObj.upload)
   {
   alert("You must enter a file name");
   return false;
   }
 else
   { return true; }
 }
</script>




Here is the start of my form:

<form action="products_insert.cfm" method="post" name="Form" onSubmit="return validateForm(this)">



Here is the file I want to validate:

<input type="file" name="upload" size="30" style="width:248px" class="fileBrowse" tabindex="5">


I must be doing something wrong, because it is not validating the form at all.  It is just going to the action page.
0
 
LVL 3

Expert Comment

by:cdillon
ID: 8241196
I think you'd need something like this:

<script LANGUAGE=JAVASCRIPT TYPE="text/javascript" >

<!--

function validateForm(myform)
{
         if (myform.image_to_upload.value.length == 0)
                Alert('Please choose a file.');
         else
                myform.submit();
         }
}


//-->
</script>


<form action="products_insert.cfm" method="post" name="image_form" onSubmit="return validateForm(this)">

<input type="file" name="image_to_upload" size="30" style="width:248px" class="fileBrowse" tabindex="5">

<input type="submit">
</form>




0
 

Author Comment

by:jeffmace
ID: 8241210
Here is what I have in the head of my page:

<script language="JavaScript" type="text/JavaScript">
function hasValue(inputObj)
 { return (inputObj.length > 0); }

function validateForm(formObj)
 {
 if (!hasValue(formObj.upload)
   {
   alert("You must enter a file name");
   return false;
   }
 else
   { return true; }
 }
</script>




Here is the start of my form:

<form action="products_insert.cfm" method="post" name="Form" onSubmit="return validateForm(this)">



Here is the file I want to validate:

<input type="file" name="upload" size="30" style="width:248px" class="fileBrowse" tabindex="5">


I must be doing something wrong, because it is not validating the form at all.  It is just going to the action page.
0
 
LVL 8

Expert Comment

by:TallerMike
ID: 8241239
Jeff, the problem is with how you are submitting your form. If you are using a submit button, then my method will work fine. If you are using a method OTHER than a submit type button to submit the form, then you'll need to do something like this:

<input type="button" onclick="validateForm(document.Form)">

function validateForm(formObj)
{
if (!hasValue(formObj.fname)
  { alert("You must enter your first name");
  return false;
  }
else if (!hasValue(formObj.lname)
  {
  alert("You must enter your last name");
  return false;
  }
else if (!hasValue(formObj.fileInput)
  {
  alert("You must enter file to load");
  return false;
  }
else
  { formObj.submit(); }
}

************************************************************************************
************************************************************************************

You should also never name your forms reserved words like 'Form'. Name them myForm, or anything else. Even though JavaScript is case sensative (so it's not really a reserved word) it's just good practice.
0
 

Author Comment

by:jeffmace
ID: 8241254
Here is what I have in the head of my page:

<script language="JavaScript" type="text/JavaScript">
function hasValue(inputObj)
 { return (inputObj.length > 0); }

function validateForm(formObj)
 {
 if (!hasValue(formObj.upload)
   {
   alert("You must enter a file name");
   return false;
   }
 else
   { return true; }
 }
</script>




Here is the start of my form:

<form action="products_insert.cfm" method="post" name="Form" onSubmit="return validateForm(this)">



Here is the file I want to validate:

<input type="file" name="upload" size="30" style="width:248px" class="fileBrowse" tabindex="5">


I must be doing something wrong, because it is not validating the form at all.  It is just going to the action page.
0
 
LVL 8

Expert Comment

by:TallerMike
ID: 8241306
jeffmace, please do not refresh the page to check for updates as it reposts your last comment. Use the "Reload This Question" link at the top of the left navigation menu.
0
 

Author Comment

by:jeffmace
ID: 8241325
Here is what I have in the head of my page:

<script language="JavaScript" type="text/JavaScript">
function hasValue(inputObj)
 { return (inputObj.length > 0); }

function validateForm(formObj)
 {
 if (!hasValue(formObj.upload)
   {
   alert("You must enter a file name");
   return false;
   }
 else
   { return true; }
 }
</script>




Here is the start of my form:

<form action="products_insert.cfm" method="post" name="Form" onSubmit="return validateForm(this)">



Here is the file I want to validate:

<input type="file" name="upload" size="30" style="width:248px" class="fileBrowse" tabindex="5">


I must be doing something wrong, because it is not validating the form at all.  It is just going to the action page.
0
 

Author Comment

by:jeffmace
ID: 8241331
sorry...i just noticed i did that...
0
 
LVL 1

Expert Comment

by:DA_JED
ID: 8242609
Hello everyone!
TallerMike, I hope you don't mind me using your code.  I like it. There are some changes that need to be made though.

JeffMace, please take TallerMike's advice.

Ok here's the code:

Everything is the same as TallerMike, but the only difference it the addition of the .value in the if statement for the hasValue function.  Once this is done, everything should work fine.




function hasValue(inputObj)
 { return (inputObj.value.length > 0); }

function validateForm(formObj)
 {
 if (!hasValue(formObj.fieldName)
   {
   alert("You must enter a file name");
   return fasle;
   }
 else
   { return true; }
 }


Then on your form:

<form onsubmit="return validateForm(this)">
0
 
LVL 10

Accepted Solution

by:
substand earned 1000 total points
ID: 8243002
use tallermike's code. i like it as well, its simple and clean.

however, i beleive the problem you are experiencing is that you are missing an end parenthesis on your if statement:

<script language="JavaScript" type="text/JavaScript">
function hasValue(inputObj)
{ return (inputObj.length > 0); }

function validateForm(formObj)
{
if (!hasValue(formObj.upload))
  {
  alert("You must enter a file name");
  return false;
  }
else
  { return true; }
}
</script>


try that.
0
 
LVL 10

Expert Comment

by:substand
ID: 8243009
oh, sorry, i think you need the inputObj.value.length as DA JED sugguested as well...
0
 
LVL 17

Expert Comment

by:anandkp
ID: 8243218
Hi Jeff,

this is what ive been using ...

<!---
1. New_FieldName = name of ur file_field on the previous page inside the form tag
2. Image_FieldName = name of the exisiting image
    [used only for deleting previous rec / id can also be used. alter the query below as required]
3. FilePath = full physical path where file needs to be uplaoded OR is uploaded
4. New_FieldName = variable used for assignign new name to the file after uplaod
    [incase of rename option being used]
5. FILEEXT = the extension of the file uploaded - so renaming can be handled properly
 --->

<CFIF ISDEFINED('New_FieldName') AND TRIM(New_FieldName) NEQ ''><!--- Upload --->
     <CFIF ACT EQ "EDIT"><!--- Del existing one - only incase of edit mode !!! --->
          <CFQUERY NAME="Del_Img" DATASOURCE="#DSN#" DBTYPE="ODBC" USERNAME="#USERNAME#" PASSWORD="#PASSWORD#">
               Select New_FieldName from TableName where New_FieldName = #Image_FieldName#
          </CFQUERY>
          <CFIF DEL_IMG.RECORDCOUNT GT 0 AND FILEEXISTS('#FILEPATH##Del_Img.New_FieldName#')>
               <CFFILE ACTION="DELETE" FILE="#FilePath##Del_Img.New_FieldName#">
          </CFIF>
          <CFSET New_FieldName = ""><!--- Since image is deleted - set it to blank --->
     </CFIF>
     <CFTRY>
         <CFFILE ACTION="UPLOAD" FILEFIELD="New_FieldName" DESTINATION="#FilePath#" NAMECONFLICT="MakeUnique">
         <CFIF ISDEFINED('Rename')><!--- Rename ! --->
            <CFSET FILEEXT = LISTLAST(FILE.SERVERFILE,'.')>                    
            <CFFILE ACTION="RENAME" SOURCE="#FilePath##FILE.SERVERFILE#" DESTINATION="#FilePath##NewFileName#.#FILEEXT#">
            <CFSET New_FieldName = "#NewFileName#.#FILEEXT#">
        <CFELSE><!--- keep original name as it is --->
            <CFSET New_FieldName = #FILE.SERVERFILE#>
        </CFIF>        
     <CFCATCH>
        <SCRIPT LANGUAGE="JavaScript" TYPE="text/javascript">
        <!--
        alert('image not selected properly pls select the image again')
        history.back(-1)
        //-->
        </SCRIPT>        
    </CFCATCH>
    </CFTRY>
     <CFQUERY name="Upd_Table">
          Update Table set ImageName = '#New_FieldName#'
     </CFQUERY>
<CFELSE>
    <!--- Keep the Image As It Is ! --->
    <!--- Dont do ne-thing here --->
</CFIF>

try it & let me know

K'Rgds
Anand
0
 
LVL 10

Expert Comment

by:substand
ID: 8243302
oh, this might help too:

in your form tag, you need to add:

enctype="multipart/form-data"

so it would now read:

<form action="products_insert.cfm" method="post" name="Form" onSubmit="return validateForm(this)" enctype="multipart/form-data">

that may fix it.
0
 
LVL 17

Expert Comment

by:anandkp
ID: 8243377
hi Jeff,

just run this code on a seperate page & see how it works

<CFSET FILEEXTENSION = "'jpeg','jpg','jpe','gif','doc','xls','pdf'">

<SCRIPT LANGUAGE="JavaScript" TYPE="text/javascript">
<!--
function ValThisForm()
{
    var sCont = document.frm.imagefield_name;
    var sContVal = document.frm.imagefield_name.value;
                             
    var res="no";
                   
    var gfile=sContVal.toLowerCase();
    var str= new String();
    str= gfile;
                       
    var finddot=str.lastIndexOf('.',str.length);
    var contain=new String();
    var contain=str.substring(finddot+1,str.length);                    
                       
    var findslash=str.lastIndexOf('\\',str.length); // checks the occurance of '.' in photoname [creates problem in uplaoding]
    var contain2=new String();
    var contain2=str.substring(findslash+1,finddot);                    
                                           
    var sSpace = sContVal.indexOf(' ')                    
    var str=new String();
    str=contain2;
    var span=new RegExp("[##]","g");
    var rep=str.replace(span,"~");
                       
    <CFSET FileNameConstraintsList = ".">
                             
    <CFLOOP INDEX="CheckList" FROM="1" TO="#ListLen(FileNameConstraintsList)#">
        <CFSET CurVal = #ListGetAt(FileNameConstraintsList,CheckList)#>
        var spans#CheckList#=new RegExp("[#CurVal#]","g");
         var rep=rep.replace(spans#CheckList#,"~");
    </CFLOOP>  
                     
    var chkindex = rep.indexOf('~')
                       
    <CFIF ISDEFINED("FileExtension") AND TRIM(FileExtension) NEQ ""> // chk for specified parameters, else can upload anything
        <CFSET ChkFileExt = FileExtension>                    
        var arr=new Array(#ChkFileExt#);
                                               
        for(i=0;i<=arr.length-1;i++)
            {                                                            
                 if(arr[i]==contain)
                  var res="yes";
            }    
    </CFIF>    
                                                     
    if(<CFIF ISDEFINED("FileExtension") AND TRIM(FileExtension) NEQ "">res != "yes" ||</CFIF> (sContVal=="") || (chkindex != -1) )
        {              
             alert("pls enter the image properly");                              
              sCont.focus();
              sCont.select();
              return false;
         }        
}

//-->
</SCRIPT>

<FORM name="frm" METHOD="post" ENCTYPE="multipart/form-data" ONSUBMIT="return ValThisForm()">
    <input TYPE="File" NAME="imagefield_name">
    <input type="submit">
</FORM>


i hope it helps u

let me know

K'Rgds
Anand
0
 
LVL 8

Expert Comment

by:TallerMike
ID: 8245731
oops, forgot about the '.value' part. I wrote it quickly. Thanks for catching it everyone.
0
 
LVL 1

Expert Comment

by:DA_JED
ID: 8247753
That's what we're here for, to help each other out.  Much respect TallerMike.

But Jeff you haven't commented in a while, you're leaving us in suspense, did it work?

DA JED
0
 

Author Comment

by:jeffmace
ID: 8247799
YEP!! THIS IS THE WORKING CODE!!!

<script language="JavaScript" type="text/JavaScript">
function hasValue(inputObj)
{ return (inputObj.length > 0); }

function validateForm(formObj)
{
if (!hasValue(formObj.upload))
 {
 alert("You must enter a file name");
 return false;
 }
else
 { return true; }
}
</script>



I want to thank all of you for your effort and ideas.  Thank God for this website :)

Jeff
0
 
LVL 8

Expert Comment

by:TallerMike
ID: 8247857
jeffmace, make sure you added the '.value' attribute to the hasValue function like so:

function hasValue(inputObj)
{ return (inputObj.value.length > 0); }
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

If you don't have the right permissions set for your WordPress location in IIS, you won't be able to perform automatic updates. Here's how to fix the problem.
When it comes to showing a 404 error page to your visitors, you do not want that generic page to show, and you especially do not want your hosting provider’s ad error page to show either. In this article, I will show you how to enable the custom 40…
Michael from AdRem Software outlines event notifications and Automatic Corrective Actions in network monitoring. Automatic Corrective Actions are scripts, which can automatically run upon discovery of a certain undesirable condition in your network.…
Add bar graphs to Access queries using Unicode block characters. Graphs appear on every record in the color you want. Give life to numbers. Hopes this gives you ideas on visualizing your data in new ways ~ Create a calculated field in a query: …

752 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question