Home > Articles > Programming > Ajax

📄 Contents

  1. 2.1 Validating Form Fields
  2. 2.2 Tutorial Step 2Adding Client-side Validation
This chapter is from the book

2.2 Tutorial Step 2—Adding Client-side Validation

In this step of the tutorial, we use Dojo to provide basic client-side validations. We look at a number of useful techniques within the context of making real enhancements to our form. One by one, we examine the fields that these techniques are appropriate for.

2.2.1 Validate the First Name Field

Let’s look at the “First Name” field first. What are the validations that we need to apply? The data on this form feeds into our billing system, so the customer’s name is very important—the field must be required. Are there any other validations? Not only do we want to get the data, but also we’d like it to be in a consistent format. Possibly the data should be stored in all capital letters. Or maybe we want to ensure that the data is not in all capitals. Let’s choose the latter—but we’ll still want to make sure that at least the first letter is capitalized. As in many of the issues related to validation, things are more complicated then they might first appear. For example, are we allowing enough room to enter long names? Will single-word names such as “Bono” be allowed? For our purposes, we’ll keep it simple.

We turn on validation by using special attribute values in the HTML markup for these fields. The following code will add validation to the fields.

    <label for="firstName">First Name: </label>
    <input type="text" id="firstName" name="firstName"

        dojoType="dijit.form.ValidationTextBox"
        required="true"
        propercase="true"
        promptMessage="Enter first name."
        invalidMessage="First name is required."
        trim="true"

    /><br>

The code is formatted to be more readable by using line breaks. To summarize what has happened: All we’ve done is add some new attributes to the <input> tag for the field. Each of the new attributes affects the validation in some way.

Notice the following line of code from the preceding example:

       dojoType="dijit.form.ValidationTextBox"

This attribute is not a standard HTML <input> tag attribute. Depending on which editor you are using to modify the file, it may even be highlighted as an error. The dojoType attribute is only meaningful to the Dojo parser, which was referenced in step 1. Remember the code we needed to include the parser? It is shown here:

       dojo.require("dojo.parser");

The parser reads through the HTML and looks for any tag that contains dojoType as one of its attributes. Then the magic happens. The parser replaces the element with the Dojo widget specified by dojoType. In this case, the widget dijit.form.ValidationTextBox is substituted for the Document Object Model (DOM) element created from the <input> tag.

How does Dojo know what to replace the tag with? That is determined by the specific widget. Each widget behaves a little differently. HTML markup and JavaScript code is associated with the widget in its definition, and that is how Dojo knows what to replace the original element with—which brings us to the missing piece of the puzzle. We need to tell Dojo to include the code for the widget by specifying the widget in JavaScript. To do that, we include the following JavaScript code after the link to Dojo and after the reference to the Dojo parser.

    dojo.require("dijit.form.ValidationTextBox");

Notice that the name of the widget specified as the value for the dojoType attribute is the same as the argument for the dojo.require call. This is the linkage that allows Dojo to associate the HTML markup with the JavaScript code for that widget.

To emphasize this process, let’s review the HTML markup specified in the original page and then compare it to the HTML markup after the parser runs. To see the original markup, we merely have to view the source of the file form.html. Seeing the new markup is a bit harder. The browser converts the original HTML into a DOM tree representing the various tags. The Dojo parser modifies the DOM elements using JavaScript, but the original source for the page is untouched. We need some tool that will convert the DOM (the browser’s internal representation of the page) back into HTML for our review. The Firefox browser provides a DOM Inspector to do just that. An excellent add-on to Firefox, called Firebug, also allows the DOM to be inspected. Firebug also provides a number of excellent tools for developing web pages such as its DOM inspection capabilities we can use to inspect the DOM after the Dojo parser has run—so we can see exactly what it does. But before we see how the DOM changes, let’s first review the original <input> tag for the first name field.

    <input
        type="text"
        id="firstName"
        size="20"
        dojoType="dijit.form.ValidationTextBox"
        required="true"
        propercase="true"
        promptMessage="Enter first name."
        invalidMessage="First name is required."
        trim="true"
    />

The code has been reformatted to make it more readable by adding some line breaks. The attributes from dojoType through trim are not valid HTML attributes. They are meaningful only to the Dojo parser and drive some features of the Dojo widget they pertain to. Now let’s see what the HTML looks like after the parser runs.

<input
  type="text"
  tabindex="0"
  maxlength="999999"
  size="20"
  class="dijitInputField dijitInputFieldValidationError dijitFormWidget"
  name="firstName"
  id="firstName"
  autocomplete="off"
  style=""
  value=""
  disabled="false"

  widgetid="firstName"
  dojoattachevent="onfocus,onkeyup,onkeypress:_onKeyPress"
  dojoattachpoint="textbox,focusNode"
  invalid="true"
  valuenow=""

/>

The preceding code has also been reformatted for readability, adding line breaks and changing the order of the attributes a little. Notice that a number of valid HTML attributes have been added to the <input> DOM element such as tabindex, class, autocomplete, and disabled. And additionally, a number of Dojo-only attributes have been added such as widgetid, dojoattachevent, dojoattachpoint, invalid, and valuenow. We look at these in more detail in Part II, “Dojo Widgets,” but for now it’s enough just to point out that the parser is rewriting our HTML. The parser is doing even more work that we can see here. It is associating various event handler functions to events that might occur on this DOM element. For instance, when the user enters or changes the value in the field, Dojo functions get called, which perform validation. And Dojo even creates objects that correspond to the HTML tags. We can’t tell that this is happening just from seeing the HTML markup, but behind the scenes, that is exactly what Dojo is doing.

Let’s review the other special Dojo attributes. Each Dojo widget has a set of properties that control its behavior. These properties are set by various Dojo widget attribute values.

  • The required="true" attribute setting tells Dojo that this field must be entered.
  • The propercase="true" attribute setting tells Dojo to reformat the field value entered by the user. In this case, the setting for propercase tells Dojo to make sure that the first letter is capitalized and subsequent letters are in lowercase. In other words, Dojo will put the entered value into the format for a typical proper noun.
  • The promptMessage="Enter first name." attribute setting tells Dojo to display a message next to the field to instruct the user on what kind of data can be entered into the field. The prompt message displays while the field is in focus.
  • The invalidMessage="First name is required." attribute setting causes Dojo to display a message next to the field if it fails the validation. In our case, if the user does not enter a value, then a message will appear.
  • The trim="true" attribute setting tells Dojo to remove any leading or trailing spaces from the entered value before sending it to the server.

Now let’s run the page and see how it behaves. Because this is the first field on the page, the field gets focus, and the cursor immediately is placed on the input area for the “First Name” field.

Notice that we get a message box that says “Enter first name.” Dojo calls this a Tool Tip, and it has dynamic behavior. It is only displayed when the field has focus (the cursor is in the field), and once the field loses focus, the message disappears. The message appears on top of any visible element below it, so there is no need to leave room for it when designing your page.

Try entering different values in the field and then press <tab> to leave the field. For example, enter “ joe “ and watch it be transformed into “Joe” with leading and trailing spaces removed and the first letter of the name capitalized.

2.2.2 Validating the Last Name Field

The last name field has the same validations as the first name field does. There is nothing extra to do for this field and nothing new to learn. Just replace the <input> tag for Last Name with the following code.

    <input type="text" id="lastName" name="lastName"
        dojoType="dijit.form.ValidationTextBox"
        required="true"
        propercase="true"
        promptMessage="Enter last name."
        invalidMessage="Last name is required."
        trim="true"
    />

2.2.3 Validating the User Name Field

We are going to allow the user to manage his or her own account information in our application. To provide some security we need the user to make up a user name that he or she can use later to sign on to the system. This field will be required, and we’d like it to always be entered in lowercase. To validate this field, we’ll use the same Dojo widget that we’ve already used, dijit.form.ValidationTextBox, but we’ll use a new attribute called lowercase to force the transformation of the entered data into all lowercase letters.

There are some additional validations we’d like to do on this field. For instance, is this user name already assigned to someone else? We could check the server for existing values. However, because this validation requires interaction with the server, we’ll save it for step 3 of the tutorial and focus on only the client-side validation right now.

The following HTML markup is needed to enable validation for this field.

    <input type="text" id="userName" name="userName"
        dojoType="dijit.form.ValidationTextBox"
        required="true"
        promptMessage="Enter user name."
        trim="true"
        lowercase="true"
    />

2.2.4 Validating the Email Address Field

We need to communicate with our customers so we’ll get their email addresses. This will be a required field. We’ll also make it all lowercase for consistency. In addition, we’d like to make sure that the value entered in this field is also in the correct format for an email address. There is no way to know if it is a working email until we actually try to send something to it, but at least we can make sure that it contains a “@” character and appears to reference a valid domain.

How can we specify the desired format? By using a specialized pattern matching language known as regular expressions, we can specify a pattern of characters to check the value against. We need to build a regular expression to validate for email addresses. At this point in our discussions, let’s not go on a long detour to discuss the building of these expressions.

The following is regular expression that can be used to validate most formats of email addresses—most because it is surprisingly difficult to validate for all possible email addresses. This is because of some of the unusual variations such as domains longer than four characters such as “.museum” or addresses consisting of a sub-domain. But the following regular expression will work for most.

[\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b]+

The ValidationTextBox contains a special property for validating against regular expressions. The attribute to use is regExp—just specify the regular expression as its value. Replace the <input> tag for email with the following code in “form.html” to specify validation for the email address field.

    <input type="text" id="email" name="email" size="30"
        dojoType="dijit.form.ValidationTextBox"
        required="true"
        regExp="\b[a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}\b"
        promptMessage="Enter email address."
        invalidMessage="Invalid Email Address."
        trim="true"
    />

Validating email addresses is a really interesting subject. There are quite a few variants to the simple name@company.com format that we often see. For a really thorough discussion of email, you should review the RFC rules. The following link will get you to the Wikipedia page that describes email, from which you can link to the official RFC documents: http://en.wikipedia.org/wiki/E-mail_address.

2.2.5 Validating the Address Field

The address field will contain the first line of the user’s mailing address. We’ll make it required. We will use the ValidationTextBox, and we have seen all of the attributes already. Replace the <input> tag for address with the following code.

    <input type="text" id="address" name="address" size="30"
        dojoType="dijit.form.ValidationTextBox"
        required="true"
        promptMessage="Enter address."
        invalidMessage="Address is required."
        trim="true"
    />

There are many additional validations that can be performed on address data, the most important being to ensure that the address is an actual address. Standard abbreviations such as “St” for “Street” could also be allowed. These additional validations could be done by a number of web services available from the U.S. Postal Service, but that is really outside the scope of this tutorial.

2.2.6 Validating the City Field

The city field will contain the value for the city in the user’s mailing address. We’ll make it required. We will use the ValidationTextBox. Replace the <input> tag for address with the following code.

    <input type="text" id="city" name="city" size="30"
        dojoType="dijit.form.ValidationTextBox"
        required="true"
        promptMessage="Enter city."
        invalidMessage="City is required."
        trim="true"
    />

2.2.7 Validating the Zip Code Field

The zip code field is part of the mailing address and is required. There are some additional validations we can apply. Our hypothetical company is a U.S. corporation and only provides service to U.S. customers, so we’ll limit our address to valid U.S. addresses, which means that the zip code must be in one of two forms. Either it is a 5-digit number, or it is a 5-digit number followed by a dash and then followed by a 4-digit number. If we can come up with a regular expression to test for either format, then we’re golden!

Replace the <input> tag for zip code with the following to enable Dojo validation for this field.

    <input type="text" id="zipCode" name="address" size="30"
        dojoType="dijit.form.ValidationTextBox"
        trim="true"
        required="true"
        regExp="\d{5}([\-]\d{4})?$"
        maxlength="10"
        promptMessage="Enter zip code."
        invalidMessage="Invalid zip code (NNNNN) or (NNNNN-NNNN)."
    />

An interesting feature of the preceding code is that we’ve got two overlapping validations. The maxlength attribute prevents the value from being over 10 digits, but so does that regular expression. What are the implications of this? One could argue that it is inefficient because both validations will be executed. But they each operate differently on the page, which might justify using both. If the user tries to enter a zip code that is 12 digits long, he will be notified as he tries to type the eleventh digit, rather than after typing all 12 digits and pressing tab to leave the field. By using both techniques, the error is detected sooner.

In this chapter we’ve focused on functionality that doesn’t require a call to the server. In the next chapter the server will play a role. We’ll make calls to the server using the XMLHttpRequest to get data and perform validations. Now that’s Ajax!

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020