1 / 28

WDMD 170 Internet Languages

eLesson: Working with Forms in JavaScript (there is an audio component to this eLesson) © Dr. David C. Gibbs 2003-04 WDMD 170 Internet Languages NOTE: click on the “Slide Show” icon in the lower right of the screen to hear the audio track

oshin
Download Presentation

WDMD 170 Internet Languages

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. eLesson: Working with Forms in JavaScript (there is an audio component to this eLesson) © Dr. David C. Gibbs 2003-04 WDMD 170 Internet Languages NOTE: click on the “Slide Show” icon in the lower right of the screen to hear the audio track

  2. Tutorial 6FormsSection B - Validating a User's Input to a Form

  3. Tutorial 6B Topics • Section B - Validating a User's Input to a Form • About hidden form fields • About the Form object • How to reference forms and form elements • About form event handlers, methods, and properties • How to e-mail form data

  4. Hidden Form Fields • Special type of form element that allows the hiding of information from users • Created with <input> tag, setting the TYPE attribute to hidden • Can be used to store information the program needs later

  5. Hidden Form Fields: the calculator example revised Code sample: Calculator.html Extends the calculator of Tutorial 3 by adding the following: • Adds the button M+ – which adds the displayed value to memory • Adds the button MRC – which recalls the stored memory value • Adds the button MC – which clears the memory • Implements the “memory” cell as a hidden form field.

  6. eTask 1 • Copy the source code for Calculator.html found in Tutorial 06 into your working Tutorial06 folder. • Create an XHTML page to explain the features of the new Calculator. • Provide a link to the calculator • Copy in the text of items 1-4 from the previous slide, and beneath each one (between <pre> tags), add the actual HTML code for each additional item. For example, here is the third one: 3. Adds the button MC – which clears the memory. Code: <input type="button" name="memClear" value="MC" onclick="document.Calculator.storedValue.value=0"> • Then explain what the code actually does. • Save your file as ModifiedCalculatorExplained.htm.

  7. The Form Object • Enables the use of JavaScript for verifying form information. • Allows validation before submission to server • Minimizes Web traffic • Simplifies server-side scripting, because only “good” data is passed • This is called “client-side” validation – as opposed to “server-side” validation.

  8. The Form Object:Referencing Forms and Form Elements • Document object includes a forms[] array that contains all of an HTML document’s forms • Like any array, subscripted [0] thru [n-1] • Form object includes an elements[] array that contains all of a form’s elements • Placed into array in order they are placed in form • To reference third element in second form: • document.forms[1].elements[2]

  9. <form> tag: NAME attribute • Allows JavaScript to reference the item (e.g., form, element, etc.) • If multiple form elements share the same name, JavaScript creates an array of those elements • Radio buttons • document.demographics.ageGroup[1].value

  10. <form> tag: event handlers • onSubmit • Executes when a form is submitted to a CGI script using a submit or an image input tag <form name="myForm" onSubmit="anotherPage.htm"> • onReset • Executes when a reset button is selected on a form <form name="myForm" onReset="return confirmReset();"> We saw these used in Tutorial 06A. Of course, both can be used in the same form tag.

  11. Validating User Input to a Form: individual form elements • Form elements we will validate • A numeric field • The length of a password field • The validity of an email address • You will implement these validation techniques in your project.

  12. eTask 2 • Actually, this is a “hands-on” task. • Load each of the validation examples given below into HTML-Kit and print them. [That way you can study them independent of the screen!] • validateNumericField.htm • validatePasswordLength.htm • validateEmailAddress.htm • These examples are examined in detail in the next several slides.

  13. Validating User Input to a Form:a numeric field • Makes use of the JS function isNaN() which returns true if the value passed is “Not a Number”. • Copy the following code into an html page and view the page: alert("5 is: " + isNaN(5)); alert("Q is: " + isNaN("Q")); • What is returned by isNaN(5)? Ans: false • What is returned by isNaN("Q")? Ans: true

  14. Validating User Input to a Form:a numeric field • Caution: the function isNaN() applied to the empty string (“”) returns false – which means it’s a number? Copy this into an html page script tag: alert(isNaN("")); and see what is displayed when you execute the script! • So you must test for the empty string as well.

  15. Validating a numeric field Code sample: validateNumericField.htm The function to check for a numeric field: • function validNumeric(myField){ • // returns true if myField is a number; false otherwise • var myValue = myField.value • if(isNaN(myValue) || myValue == ""){ • alert("You must enter a valid number!"); • myField.value = ""; • return false; • } else • return true; • }

  16. Validating User Input to a Form:length of a password field • Many passwords must be a certain minimum and maximum length. • Text fields (i.e. <input type=“text”… ) can have a maxlength attribute. <input type="password" maxlength="10"> Anything more than 10 is ignored by the code using the text field. • But - the minimum length must be validated.

  17. Validating the length of a password Code sample: validatePasswordLength.htm To check the minimum length, reference the .length attribute of the value. • function checkStrLength(txtBox, len) { • // returns false if length of the txtbox field < len • if (txtBox.value.length < len){ • alert('Your password must be at least ' + len + ' characters long'); • txtBox.value=""; • txtBox.focus(); • return false; • } else • return true; • }

  18. Validating User Input to a Form:an email address A valid email address is in the form a@b.c A validation routine would verify 5 pieces: • a string of one or more characters, followed by, • a lower case “at-sign”, @, followed by, • a string of one or more characters, followed by, • a period “.”, followed by, • a string of one or more characters. Doing this with string methods would be a nightmare!

  19. Validating an email address: regular expressions • JavaScript contains a powerful technique available in most programming languages – regular expressions. • A regular expression is a pattern used to match character combinations in strings. • We will use a prepared function that uses regular expressions to validate email addresses. • You only need to be able to invoke the function from within your code.

  20. Validating using regular expressions Code sample: validateEmailAddress.htm The regular expression is in line 2. If you look closely, you can find the mandatory “@” and “.” characters. Line 3 compares the value to be checked against the “filter”. • function validEmailAddr(checkMe) { • var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9])+$/; • if (filter.test(checkMe)) • return true • else { • return false; • } • } Again, the good news is at this stage all you have to do is USE it! Refer to the sample code above for implementation details!

  21. Validatation: putting it all together Code sample: validateEmailAddress.htm <form name="frmInfo" onSubmit="validateDataFields();" onReset='return confirm("Are you sure you wish to reset the form?");'>

  22. Validatation: putting it all together Code sample: validateEmailAddress.htm • function validateDataFields() { • var goodStr = checkStrLength(document.frmInfo.txtUsername, 6); • var goodNumber = validNumeric(document.frmInfo.txtAge); • var goodEmail = checkEmailAddress(document.frmInfo.txtEmailAddr); • if ((goodStr == true) && (goodNumber == true) && (goodEmail == true)) { • alert("Good data! Submitting now!"); • } • }

  23. E-Mailing Form Data • Instead of submitting data to a server, it can be transferred to an e-mail address • Much simpler than creating scripts on the server • Recipient must then process information • Use ENCTYPE = “text/plain” • In the form’s ACTION attribute use “mailto:email_address”

  24. E-Mailing Form Data: example Code sample: eMailingFormData.htm <form action = "mailto:president@whitehouse.gov" method = "post" enctype="text/plain" name="voter_information"> Note that the mailto: value has some interesting additions to tweak the mail header fields (see Musciano page 172 for more information). mailto:president@whitehouse.gov?subject=Iraq?cc=vicepresident@whitehouse.gov This fills in the Subject: and Cc: fields in most mail programs.

  25. Result of using “mailto:”

  26. Summary Validating User Input within Forms in JavaScript • Hidden form fields; how they work, how they are used • The Form object, its attributes, and how to reference forms and form elements • Form event handlers, methods, and properties • Validating input: numeric fields, string length, email addresses • How to e-mail form data

  27. Assignment • Complete exercise #7 on page 361 of Gosselin, Tutorial 06B. The text of the exercise is copied in here, with additions:Create an RSVP form for a party you are hosting. Your guests should fill out the form supplying the following: their name, phone number, and the number of people coming with them, and submit it to your email address. Your code should verify that the number of people field is genuinely a number. If it is not, present an alert message informing them so. Save the HTML document as RSVP.htm in your Tutorial06 folder. • Post your solution for exercise #7 to your Tutorial06 folder on the CISSRV3 server. • Continue working on the form for your project. Add validation one field at a time, starting with a numeric field, then adding the length of a password field, and then validate an email address. • Add a link in the discussion forum for your project’s form along with any questions or problems you experienced. • You may also post any questions (and the exercise file) to the eReview group – for discussion purposes.

  28. End of eLesson • Jump to the Beginning of this eLesson • WDMD 170 Course Schedule • D2L Courseware Site

More Related