⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ch07_02.htm

📁 用perl编写CGI的好书。本书从解释CGI和底层HTTP协议如何工作开始
💻 HTM
📖 第 1 页 / 共 2 页
字号:
<?label 7.2. Forms?><html><head><title>Forms (CGI Programming with Perl)</title><link href="../style/style1.css" type="text/css" rel="stylesheet" /><meta name="DC.Creator" content="Scott Guelich, Gunther Birznieks and Shishir Gundavaram" /><meta scheme="MIME" content="text/xml" name="DC.Format" /><meta content="en-US" name="DC.Language" /><meta content="O'Reilly & Associates, Inc." name="DC.Publisher" /><meta scheme="ISBN" name="DC.Source" content="1565924193L" /><meta name="DC.Subject.Keyword" content="stuff" /><meta name="DC.Title" content="CGI Programming with Perl" /><meta content="Text.Monograph" name="DC.Type" /></head><body bgcolor="#ffffff"><img src="gifs/smbanner.gif" alt="Book Home" usemap="#banner-map" border="0" /><map name="banner-map"><area alt="CGI Programming with Perl" href="index.htm" coords="0,0,466,65" shape="rect" /><area alt="Search this book" href="jobjects/fsearch.htm" coords="467,0,514,18" shape="rect" /></map><div class="navbar"><table border="0" width="515"><tr><td width="172" valign="top" align="left"><a href="ch07_01.htm"><img src="../gifs/txtpreva.gif" alt="Previous" border="0" /></a></td><td width="171" valign="top" align="center"><a href="index.htm">CGI Programming with Perl</a></td><td width="172" valign="top" align="right"><a href="ch07_03.htm"><img src="../gifs/txtnexta.gif" alt="Next" border="0" /></a></td></tr></table></div><hr align="left" width="515" /><h2 class="sect1">7.2. Forms</h2><p>Probably the most popular use for JavaScript with web applications isto improve HTML <a name="INDEX-1528" />forms. Standard HTML formsaren't very smart. They simply accept input and pass it on tothe web server where all the processing must occur. With JavaScript,however, we can do much more on the client side. JavaScript canvalidate input before it is sent to the server. Forms can alsodynamically react to user input and update fields in order to provideimmediate feedback to the user; a dynamic form can often substitutefor multiple static forms.</p><p>The benefit JavaScript provides for the server is that it shifts somework that might otherwise be done on the server to the client, and itreduces the number of server requests. The benefit JavaScriptprovides to the user is that it provides immediate feedback without adelay while the browser fetches a new page.</p><a name="ch07-3-fm2xml" /><div class="sect2"><h3 class="sect2">7.2.1. Input Validation</h3><p>When you <a name="INDEX-1529" /> <a name="INDEX-1,530" /> <a name="INDEX-1,531" /> <a name="INDEX-1,532" />create an HTML form, you generallyexpect the user to fill it out in a particular way. There arenumerous types of restrictions a form may have. For example, some ofthe fields may only accept numbers while others may only acceptdates, some fields may only accept a certain range of entries, somefields may be required, and some combinations of fields may notpermitted. All of these examples must be handled by only two types ofchecks: the first is to validate each element user's input asthe data is entered; the second is to perform the validation when theform is submitted.</p><a name="ch07-4-fm2xml" /><div class="sect3"><h3 class="sect3">7.2.1.1. Validating elements</h3><p>Checking a <a name="INDEX-1533" /><a name="INDEX-1534" /><a name="INDEX-1535" />formelement when the user enters a value is most effective for validatingthe format or range of a particular element. For example, if a fieldonly accepts numbers, you can verify that the user did not enter anynon-numeric characters.</p><p>To perform this check, we use the<tt class="function">onChange</tt><a name="INDEX-1536" /> event handler. This handler supportsthe following form elements: <a name="INDEX-1537" /><a name="INDEX-1538" /> <a name="INDEX-1,539" />Text, TextArea, Password, FileUpload, and <a name="INDEX-1540" />Select. For each of these elements, we canregister an <tt class="function">onChange</tt> handler and assign it codeto execute when the element changes. We register it simply by addingit as an attribute to the <a name="INDEX-1541" />HTML tag that creates the element. Forexample:</p><blockquote><pre class="code">&lt;INPUT TYPE="text" name="age" onChange="checkAge( this );"&gt;</pre></blockquote><p>This runs the function<tt class="function">checkAge</tt><a name="INDEX-1542" /> and passes it a reference toitself via <tt class="literal">this</tt>. <tt class="function">checkAge</tt>looks like this:</p><blockquote><pre class="code">function checkAge ( element ) {    if ( element.value != parseInt( element.value ) ||         element.value &lt; 1 || element.value &gt; 150 ) {        alert( "Please enter a number between 1 and 150 for age." );        element.focus(  );        return false;    }    return true;}</pre></blockquote><p>This function checks that the age entered is an integer and between 1and 150 (sorry if you happen to be 152, but we have to draw the linesomewhere).</p><p>If <tt class="function">checkAge </tt>determines that the input isinvalid, it displays an alert asking the user to enter the valueagain (<a href="ch07_02.htm#ch07-86604">Figure 7-1</a>), and moves the cursor back tothe age field via <tt class="literal">element.focus()</tt><a name="INDEX-1543" /><a name="INDEX-1544" />. It then returns true or falsedepending on whether the check was successful or not. Thisisn't necessary, but it does help us if we later decide tostring multiple function calls together as you'll see later in<a href="ch07_02.htm#ch07-17670">Example 7-2</a>.</p><a name="ch07-86604" /><div class="figure"><img width="368" src="figs/cgi2.0701.gif" height="130" alt="Figure 7-1" /></div><h4 class="objtitle">Figure 7-1. JavaScript alert</h4><p>Note that we don't need to call a function to handle<tt class="function">onChange</tt>. We can assign multiple statementsdirectly to the<tt class="function">onChange</tt><a name="INDEX-1545" /> handler. However, it's often mucheasier to work with HTML documents when the JavaScript is kepttogether as much as possible, and functions help us to do this. Theyalso allow us to share code when we have multiple form elements thatrequire the same validation. For functions that you use often, youcan go a step further and place these in a JavaScript file that youcan include in multiple HTML files. We'll see an example ofthis in <a href="ch07_02.htm#ch07-45880">Figure 7-2</a>.</p></div><a name="ch07-5-fm2xml" /><div class="sect3"><h3 class="sect3">7.2.1.2. Validating submits</h3><p>The other way that we<a name="INDEX-1546" /><a name="INDEX-1547" /> <a name="INDEX-1,548" />can performdata validation is to do so just before the form is submitted. Thisis the best time to check whether required fields have been filled orto perform checks that involve dependencies between multipleelements. We perform this check with JavaScript's<tt class="function">onSubmit</tt><a name="INDEX-1549" /><a name="INDEX-1550" /><a name="INDEX-1551" /> handler.</p><p><em class="emphasis">onSubmit</em> works like the<tt class="function">onChange</tt> handler except that it is added as anattribute of the &lt;FORM&gt; tag:</p><blockquote><pre class="code">&lt;FORM METHOD="POST" ACTION="/cgi/register.cgi" onSubmit="return checkForm(this);"&gt;</pre></blockquote><p>There's another difference you may notice. The<tt class="function">onSubmit</tt> handler returns the value of the codethat it calls. If the <tt class="function">onSubmit</tt> handler returnsfalse, it cancels the submission of the form after the handler codehas run. In any other case, the form submission continues. Returnvalues have no effect on the <tt class="function">onChange</tt> handler.</p><p>Here is the function that <a name="INDEX-1552" />checks our form:</p><blockquote><pre class="code">function checkForm ( form ) {    if ( form["age"].value == "" ) {        alert( "Please enter your age." );        return false;    }    return true;}</pre></blockquote><p>This example simply verifies that a value was entered for age.Remember, our <tt class="function">onChange</tt> handler is not enough todo this because it is only run when the value for age changes. If theuser never fills in a value for age, the<tt class="function">onChange</tt> handler will never be called. This iswhy we check for required values with <tt class="function">onSubmit</tt>.</p></div><a name="ch07-6-fm2xml" /><div class="sect3"><h3 class="sect3">7.2.1.3. Validation example</h3><p>Let's look at a <a name="INDEX-1553" /> <a name="INDEX-1,554" />completeexample. It seems that more and more web sites want users to registerand provide lots of personal information in order to use their website. We'll create a slightly exaggerated version of aregistration form (<a href="ch07_02.htm#ch07-45880">Figure 7-2</a>).</p><a name="ch07-45880" /><div class="figure"><img width="481" src="figs/cgi2.0702.gif" height="398" alt="Figure 7-2" /></div><h4 class="objtitle">Figure 7-2. Our sample user registration form</h4><p>Note that this form applies only to United States residents. Inpractice, Internet users come from around the world, so you must beflexible with your validation to accommodate the variousinternational formats for phone numbers, postal codes, etc. However,since the purpose of this example is to demonstrate validation,we'll restrict the formats to one set that can be easilyvalidated. The required formats for phone numbers and social securitynumbers are shown. In addition, the zip code is a five-digit postalcode.</p><p>The HTML is shown in <a href="ch07_02.htm#ch07-57105">Example 7-1</a>.</p><a name="ch07-57105" /><div class="example"><h4 class="objtitle">Example 7-1. input_validation.html </h4><a name="INDEX-1557" /><a name="INDEX-1,558" /><blockquote><pre class="code">&lt;html&gt;  &lt;head&gt;    &lt;title&gt;User Registration&lt;/title&gt;    &lt;script src="/js-lib/formLib.js"&gt;&lt;/script&gt;    &lt;script&gt;&lt;!--      function validateForm ( form ) {                    requiredText = new Array( "name", "address", "city", "zip",                                    "home_phone", "work_phone", "age",                                    "social_security", "maiden_name" );                    requiredSelect = new Array( "state", "education" );          requiredRadio  = new Array( "gender" );                    return requireValues ( form, requiredText   ) &amp;&amp;                 requireSelects( form, requiredSelect ) &amp;&amp;                 requireRadios ( form, requiredRadio  ) &amp;&amp;                 checkProblems (  );      }    // --&gt;    &lt;/script&gt;  &lt;/head&gt;    &lt;body bgcolor="#ffffff"&gt;        &lt;h2&gt;User Registration Form&lt;/h2&gt;        &lt;p&gt;Hi, in order for you to access our site, we'd like first to get as      much personal information as we can from you in order to sell to other      companies. You don't mind, do you? Great! Then please fill this out as      accurately as possible.&lt;/p&gt;        &lt;p&gt;Note this form is for U.S. residents only. Others should use the      &lt;a href="intl_registration.html"&gt;International Registration      Form&lt;/a&gt;.&lt;/p&gt;        &lt;hr&gt;        &lt;form method="POST" action="/cgi/register.cgi"      onSubmit="return checkValues( this, requiredText ) &amp;&amp; checkMenus"&gt;    &lt;form method="GET" onSubmit="return validateForm( this );"&gt;      &lt;table border=0&gt;        &lt;tr&gt;&lt;td&gt;            Name:          &lt;/td&gt;&lt;td&gt;            &lt;input type="text" name="name" size="30" maxlength="30"&gt;          &lt;/td&gt;&lt;/tr&gt;        &lt;tr&gt;&lt;td&gt;            Address:          &lt;/td&gt;&lt;td&gt;            &lt;input type="text" name="address" size="40" maxlength="50"&gt;          &lt;/td&gt;&lt;/tr&gt;        &lt;tr&gt;&lt;td&gt;            City:          &lt;/td&gt;&lt;td&gt;            &lt;input type="text" name="city" size="20" maxlength="20"&gt;          &lt;/td&gt;&lt;/tr&gt;        &lt;tr&gt;&lt;td&gt;            State:          &lt;/td&gt;&lt;td&gt;            &lt;select name="state" size="1"&gt;              &lt;option value=""&gt;Please Choose a State&lt;/option&gt;              &lt;option value="AL"&gt;Alabama&lt;/option&gt;              &lt;option value="AK"&gt;Alaska&lt;/option&gt;              &lt;option value="AZ"&gt;Arizona&lt;/option&gt;                  .                  .                  .              &lt;option value="WY"&gt;Wyoming&lt;/option&gt;            &lt;/select&gt;          &lt;/td&gt;&lt;/tr&gt;        &lt;tr&gt;&lt;td&gt;            Zip Code:          &lt;/td&gt;&lt;td&gt;            &lt;input type="text" name="zip" size="5" maxlength="5"                onChange="checkZip( this );"&gt;          &lt;/td&gt;&lt;/tr&gt;        &lt;tr&gt;&lt;td&gt;            Home Phone Number:          &lt;/td&gt;&lt;td&gt;            &lt;input type="text" name="home_phone" size="12" maxlength="12"              onChange="checkPhone( this );"&gt;            &lt;i&gt;(please use this format: 800-555-1212)&lt;/i&gt;          &lt;/td&gt;&lt;/tr&gt;        &lt;tr&gt;&lt;td&gt;            Work Phone Number:          &lt;/td&gt;&lt;td&gt;            &lt;input type="text" name="work_phone" size="12" maxlength="12"              onChange="checkPhone( this );"&gt;            &lt;i&gt;(please use this format: 800-555-1212)&lt;/i&gt;          &lt;/td&gt;&lt;/tr&gt;        &lt;tr&gt;&lt;td&gt;            Social Security Number (US residents only):          &lt;/td&gt;&lt;td&gt;            &lt;input type="text" name="social_security" size="11" maxlength="11"              onChange="checkSSN( this );"&gt;            &lt;i&gt;(please use this format: 123-45-6789)&lt;/i&gt;          &lt;/td&gt;&lt;/tr&gt;        &lt;tr&gt;&lt;td&gt;            Mother's Maiden Name:          &lt;/td&gt;&lt;td&gt;            &lt;input type="text" name="maiden_name" size="20" maxlength="20"&gt;          &lt;/td&gt;&lt;/tr&gt;        &lt;tr&gt;&lt;td&gt;            Age:          &lt;/td&gt;&lt;td&gt;            &lt;input type="text" name="age" size="3" maxlength="3"              onChange="checkAge( this );"&gt;          &lt;/td&gt;&lt;/tr&gt;        &lt;tr&gt;&lt;td&gt;            Gender:          &lt;/td&gt;&lt;td&gt;            &lt;input type="radio" name="gender" value="male"&gt; Male            &lt;input type="radio" name="gender" value="female"&gt; Female          &lt;/td&gt;&lt;/tr&gt;        &lt;tr&gt;&lt;td&gt;            Highest Education:          &lt;/td&gt;&lt;td&gt;            &lt;select name="education" size="1"&gt;              &lt;option value=""&gt;Please Choose a Category&lt;/option&gt;              &lt;option value="grade"&gt;Grade School&lt;/option&gt;              &lt;option value="high"&gt;High School Graduate (or GED)&lt;/option&gt;              &lt;option value="college"&gt;Some College&lt;/option&gt;              &lt;option value="junior"&gt;Technical or Junior College Degree&lt;/option&gt;              &lt;option value="bachelors"&gt;Four Year College Degree&lt;/option&gt;              &lt;option value="graduate"&gt;Post Graduate Degree&lt;/option&gt;

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -