1 / 38

CSC 3084: Web Development and Programming

CSC 3084: Web Development and Programming. Chapter 10: How to Work with Forms and Data Validation. Chapter Overview. By the end of this chapter, you should be able to : Use any of the jQuery selectors, methods, and event methods for working with a form in a jQuery application.

Download Presentation

CSC 3084: Web Development and Programming

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. CSC 3084:Web Development and Programming Chapter 10: How to Work with Forms and Data Validation

  2. Chapter Overview • By the end of this chapter, you should be able to: • Use any of the jQuery selectors, methods, and event methods for working with a form in a jQuery application. • Use the Validation plugin to validate the data in a form and to submit the validated data to the web server for processing. • In general terms, describe the use of the HTML5 controls and attributes for getting and validating user entries. • Describe the use of jQuery for working with forms and controls.

  3. A Form in a Web Browser

  4. The HTML for the Form <form id="email_form" name="email_form" action="join.php" method="get"> <label for="email_address">Email Address:</label> <input type="text" id="email_address" name="email_address"> <br> <label for="first_name">First Name:</label> <input type="text" id="first_name" name="first_name"> <br> <label>&nbsp;</label> <input type="submit" id="join_list" value="Join our List"> <br> </form> • The URL that’s sent when the form is submitted:join.php?email_address=judy%40murach.com&first_name=Judy

  5. The HTML for the Form <form id="email_form" name="email_form" action="join.php" method="get"> <label for="email_address">Email Address:</label> <input type="text" id="email_address" name="email_address"> <br> <label for="first_name">First Name:</label> <input type="text" id="first_name" name="first_name"> <br> <label>&nbsp;</label> <input type="submit" id="join_list" value="Join our List"> <br> </form> • The URL that’s sent when the form is submitted:join.php?email_address=judy%40murach.com&first_name=Judy

  6. Forms • An HTML form consists of one or more controls, such as text boxes and buttons, for getting input from the user • Forms have several important attributes: name A name that can be used by client-side or server- side code action The URL of the file that will process the form data method The method for submitting the form data: “get” or “post” target Where to open the page that’s specified in theaction attribute. e.g., _blank to open the page in a new window or tab.

  7. Forms (cont.) • With the post method, the form data is packaged as part of an HTTP request, and the form’s data values are hidden • With the get method, the form data is sent as part of the URL, with data values separated by ampersands • This allows the URL to be bookmarked • When the user clicks submit button, the form data is sent to the server • A reset button is used to reset a form to its default values • Data validation refers to checking the data collected by a form to make sure it is valid. This can be done in several ways, such as with HTML/CSS and/or JavaScript. Usually done on the client side.

  8. Example Form <form name="email_form" action="subscribe.php" method="post"> <p>Please enter your e-mail address to subscribe to our newsletter.</p> <p>E-Mail: <input type="text" name="email"></p> <p><input type="submit" name="submit" value="Subscribe"></p> </form>

  9. Example Buttons <input type="button" name="message" value="Alert Me"> <input type="submit" name="checkout" value="Checkout"> <input type="reset" name="resetform" value="Reset"> <input type="image" src="images/submit.jpg" alt="Submit button" width="114" height="42"> <button type="submit"> <imgsrc="images/addtocart.png" width="30" height="23" alt="Add to Cart">Add to Cart </button>

  10. Example Text Fields Quantity:<input type="text" name="quantity" value="1" size="5" readonly><br><br> Username:<input type="text" name="username" autofocus><br><br> Password:<input type="password" name="password" maxlength="6" placeholder="Enter your password"> <br><br> Hidden:<input type="hidden" name="productid" value="widget">

  11. Example Text Fields Quantity:<input type="text" name="quantity" value="1" size="5" readonly><br><br> Username:<input type="text" name="username" autofocus><br><br> Password:<input type="password" name="password" maxlength="6" placeholder="Enter your password"> <br><br> Hidden:<input type="hidden" name="productid" value="widget">

  12. Radio Button and Check Boxes Examples Crust:<br> <input type="radio" name="crust" value="thin"> Thin Crust<br> <input type="radio" name="crust" value="deep" checked> Deep Dish<br> <input type="radio" name="crust" value="hand"> Hand Tossed<br><br> Toppings:<br> <input type="checkbox" name="topping1" value="pepperoni"> Pepperoni<br> <input type="checkbox" name="topping2" value="mushrooms"> Mushrooms<br> <input type="checkbox" name="topping3" value="olives"> Olives

  13. Radio Button and Check Boxes Examples Crust:<br> <input type="radio" name="crust" value="thin"> Thin Crust<br> <input type="radio" name="crust" value="deep" checked> Deep Dish<br> <input type="radio" name="crust" value="hand"> Hand Tossed<br><br> Toppings:<br> <input type="checkbox" name="topping1" value="pepperoni"> Pepperoni<br> <input type="checkbox" name="topping2" value="mushrooms"> Mushrooms<br> <input type="checkbox" name="topping3" value="olives"> Olives

  14. Other Controls • HTML supports other form controls too, like drop-down lists, list boxes, text areas, among others

  15. HTML5 Data Validation • HTML5 adds new features to validate (error-check) data entered into a form without the need for client-side or server-side processing • Auto-completion displays a list of entry options when the user starts the entry for a field • Options based on entries user has previously made • Fields can be set to be required before processing • Default error message is browser-dependent, but can be overridden

  16. Additional Form Controls • HTML5 introduced new controls for dealing with email addresses, URLs (we just saw that in the datalist example) and telephone numbers. You can use regexes instead if you want. • These assign semantic meaning to the controls • The type attribute for email, url, and tel controls • email Control for entering email addresses. Browser will attempt to validate it as an email address. • url Control for entering URLs. Browser will attempt to validate it as an email address. • telControl for entering telephone numbers. Browsers currently don’t attempt to validate them. (Why?)

  17. email, url, and telExample <form name="email_form" action="survey.php" method="post"> <h3>Your information:</h3> <label for="email">Your email address:</label> <input type="email" name="email" id="email" required><br> <label for="link">Your web site:</label> <input type="url" name="link" id="link" list="links"><br> <label for="phone">Your phone number:</label> <input type="tel" name="phone" id="phone" required><br><br> <input type="submit" name="submit" value="Submit Survey"> </form>

  18. email, url, and telExample <form name="email_form" action="survey.php" method="post"> <h3>Your information:</h3> <label for="email">Your email address:</label> <input type="email" name="email" id="email" required><br> <label for="link">Your web site:</label> <input type="url" name="link" id="link" list="links"><br> <label for="phone">Your phone number:</label> <input type="tel" name="phone" id="phone" required><br><br> <input type="submit" name="submit" value="Submit Survey"> </form>

  19. Number and Range Controls • HTML5 includes some new controls for selecting numbers • A number control shows a box with up/down arrows • A range control shows a slider for selecting a number • These controls are partially supported in modern browsers • Attributes for the number and rangecontrols: • min The minimum value that may be entered • max The maximum value that may be entered • step The value that the numeric entry is increased or decreased by when the user uses the control

  20. Number and Range Controls <h3>Your information:</h3> <form name="test_form" action="test.php" method="get"> <label for="investment">Monthly investment: </label> <input type="number" name="investment" id="investment" min="100" max="1000" step="100" value="300"><br><br> <label for="book">Rate the book from 1 to 5: </label> <input type="range" name="book" id="book" min="1" max="5" step="1"><br><br> <input type="submit" name="submit" value="Submit Survey"> </form>

  21. Number and Range Controls <h3>Your information:</h3> <form name="test_form" action="test.php" method="get"> <label for="investment">Monthly investment: </label> <input type="number" name="investment" id="investment" min="100" max="1000" step="100" value="300"><br><br> <label for="book">Rate the book from 1 to 5: </label> <input type="range" name="book" id="book" min="1" max="5" step="1"><br><br> <input type="submit" name="submit" value="Submit Survey"> </form>

  22. Date and Time Controls • HTML5 introduces new controls for entering dates and times • Support for these controls is almost non-existent so far, but we can hope (assume?) that they will be supported as time goes on

  23. Date and Time Controls Example Date and time:&nbsp;&nbsp; <input type="datetime" name="datetime"><br><br> Local date and time:&nbsp;&nbsp; <input type="datetime-local" name="datetimelocal"><br><br> Month:&nbsp;&nbsp; <input type="month" name="month"><br><br> Week:&nbsp;&nbsp; <input type="week" name="week"><br><br> Time:&nbsp;&nbsp; <input type="time" name="time"><br><br> Date:&nbsp;&nbsp; <input type="date" name="date">

  24. Date and Time Controls Example Date and time:&nbsp;&nbsp; <input type="datetime" name="datetime"><br><br> Local date and time:&nbsp;&nbsp; <input type="datetime-local" name="datetimelocal"><br><br> Month:&nbsp;&nbsp; <input type="month" name="month"><br><br> Week:&nbsp;&nbsp; <input type="week" name="week"><br><br> Time:&nbsp;&nbsp; <input type="time" name="time"><br><br> Date:&nbsp;&nbsp; <input type="date" name="date">

  25. Regular Expressions (Regexes) • A regular expression is a standard language that provides a way to match a user entry against a pattern of characters • Writing regular expressions from scratch can be a tricky proposition, so your best bet is to work from existing code and modify as needed • There are many tutorials on the web for writing regular expressions. You should do some research on the web if you want to know more about them and to find additional examples. • Also note that there are often many different regular expressions that can be used to express the same pattern

  26. Regular Expressions (Regexes) • Attributes for using regular expressions • pattern The regular expression itself • title Text displayed in the tooltip when the mousehovers over a text field • Used for: Pattern: • Password (6+ alphanumeric) [a-zA-Z0-9]{6,} • Zip code (99999 or 99999-9999) \d{5}([\-]\d{4})? • Phone number (999-999-9999) \d{3}[\-]\d{3}[\-]\d{4} • Date (MM/DD/YYYY) [01]?\d\/[0-3]\d\/\d{4} • URL (starting with http:// or https://) https?://.+ • Credit card (9999-9999-9999-9999) ^\d{4}-\d{4}-\d{4}-\d{4}$

  27. HTML that Uses Regexes Name: <input type="text" name="name" required autofocus><br> Zip: <input type="text" name="zip" required pattern="\d{5}([\-]\d{4})?" title="Must be 99999 or 99999-9999"><br> Phone: <input type="text" name="phone" required pattern="\d{3}[\-]\d{3}[\-]\d{4}" title="Must be 999-999-9999"><br> <input type="submit" name="submit" value="Submit Survey">

  28. HTML that Uses Regexes Name: <input type="text" name="name" required autofocus><br> Zip: <input type="text" name="zip" required pattern="\d{5}([\-]\d{4})?" title="Must be 99999 or 99999-9999"><br> Phone: <input type="text" name="phone" required pattern="\d{3}[\-]\d{3}[\-]\d{4}" title="Must be 999-999-9999"><br> <input type="submit" name="submit" value="Submit Survey">

  29. More on Validation • CSS can be used to style controls that are required, which contain valid input, or which contain invalid input • CSS3 pseudo-classes for validation: :required :valid :invalid • You can code CSS rules that modify text fields that do not validate properly. For instance, you could code the :invalid fields to be displayed with a red border. input:invalid { border: 1px solid red;}

  30. When You Need JavaScript for Data Validation • The HTML5 features for data validation aren’t implemented by all current browsers, and the ones that are implemented aren’t always implemented the same way. • HTML5 is limited in the types of validation it can do. • For instance, you can’t use only HTML5 to check whether two text fields match. Consider a form that asks you to type in your password twice when creating an account.

  31. jQuery for Working with Forms • jQuery provides selectors, methods and event methods for working with forms and for validating input • First let’s look at some of the selectors: :input All form elements :text All text boxes :radio All radio buttons :checkbox All check boxes :password All password fields :submit All submit buttons :checked All check boxes and radio buttons that are checked :button All buttons :disabled All disabled elements

  32. jQuery Methods for Values val()Sets the value of a text box or other control val(value)Sets the value of a text box or other control trim()Removes all spaces at the start and end of a string

  33. Examples of These Methods • How to get the value of a numeric entry from a text box:var age = parseInt($("#age").val()); • How to trim the value of an entry and put it back into the same text box:varfirstName = $("#first_name").val().trim();$("#first_name").val(firstName); • How to get the value of the checked radio button in a group:varradioButton= $("input[name='contact_by']:checked").val(); • How to get an array of the selected options from a list:varselectOptions = [];selectOptions= $("#select_list :selected");

  34. jQuery Event Methods for Forms focus(handler)Handler runs when focus moves to the selected element blur(handler) Runs when focus leaves the element change(handler)Runs when the element’s value is changed select(handler) Runs when the user selects the text in a text box or textarea submit(handler) Runs when a submit button is clicked • For each of these methods there is one with the same name that takes no parameters which trigger the events. For instance, focus() causes the event handler function to be called on the selected element

  35. Handler Example • A handler that disables or enables radio buttons when a check box is checked or unchecked:// the change event for a check box $("#contact_me").change( function(){ if ($("#contact_me").attr("checked")) { $(":radio").attr("disabled", false) } else { $(":radio").attr("disabled", true) } });

  36. Handler Triggering Example • A handler that triggers the submit event after some data validation:$(document).ready(function() { $("#join_list").click( // join_list is a button, function() { // not a submit button // data validation code $("#email_form").submit(); } // end function ); // end click }); // end ready

  37. Form Validation Example • See JS Textbook Files\book_apps\ch10\member_form_js

  38. jQuery Validation Plugin • This plugin was written by JörnZaefferer • See jqueryvalidation.org • It works using a map of name/value pairs that indicate how each form element should be formatted to validate correctly • A second map lets you provide custom error messages for the fields you want to validate • See JS Textbook Files\book_apps\ch10\member_form_validation

More Related