Csc 3084 web development and programming
This presentation is the property of its rightful owner.
Sponsored Links
1 / 38

CSC 3084: Web Development and Programming PowerPoint PPT Presentation


  • 56 Views
  • Uploaded on
  • Presentation posted in: General

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.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -

Presentation Transcript


Csc 3084 web development and programming

CSC 3084:Web Development and Programming

Chapter 10:

How to Work with Forms and Data Validation


Chapter overview

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.


A form in a web browser

A Form in a Web Browser


The html for the form

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


The html for the form1

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


Forms

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:

    nameA name that can be used by client-side or server-side code

    actionThe URL of the file that will process the form data

    methodThe method for submitting the form data: “get” or“post”

    targetWhere to open the page that’s specified in theaction attribute. e.g., _blank to open the page ina new window or tab.


Forms cont

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.


Example form

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>


Example buttons

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>


Example text fields

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">


Example text fields1

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">


Radio button and check boxes examples

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


Radio button and check boxes examples1

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


Other controls

Other Controls

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


Html5 data validation

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


Additional form controls

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

    • emailControl for entering email addresses. Browser willattempt to validate it as an email address.

    • urlControl 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?)


Email url and tel example

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>


Email url and tel example1

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>


Number and range controls

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:

    • minThe minimum value that may be entered

    • maxThe maximum value that may be entered

    • stepThe value that the numeric entry is increased ordecreased by when the user uses the control


Number and range controls1

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>


Number and range controls2

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>


Date and time controls

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


Date and time controls example

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">


Date and time controls example1

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">


Regular expressions regexes

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


Regular expressions regexes1

Regular Expressions (Regexes)

  • Attributes for using regular expressions

    • patternThe regular expression itself

    • titleText 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}$


Html that uses regexes

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">


Html that uses regexes1

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">


More on validation

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;}


When you need javascript for data validation

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.


Jquery for working with forms

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:

    :inputAll form elements

    :textAll text boxes

    :radioAll radio buttons

    :checkboxAll check boxes

    :passwordAll password fields

    :submit All submit buttons

    :checkedAll check boxes and radio buttons that are checked

    :buttonAll buttons

    :disabledAll disabled elements


Jquery methods for values

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


Examples of these methods

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");


Jquery event methods for forms

jQuery Event Methods for Forms

focus(handler)Handler runs when focus moves to theselected 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 atext 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


Handler example

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) }

    });


Handler triggering example

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


Form validation example

Form Validation Example

  • See JS Textbook Files\book_apps\ch10\member_form_js


Jquery validation plugin

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


  • Login