Chapter 17. Data and Persistence

We can animate and interact, stream, play, and render, but we always come back to the data. Data is the foundation on which we build the majority of our JavaScript applications. In Chapter 14, we split data from the view, but in Chapter 16, we twisted them tightly back together again. In Chapter 15, we sent data back and forth between client and server, and in Chapter 13, we manipulated data using a host of APIs. Data and JavaScript, friends forever.

In this chapter, we’re going to look at ways we can persist both data and state using JavaScript in the client, and on the server. We’re also going to take a quick look at validating data before we store it.

Validating Form Data

Problem

Your web application gathers data from the users using HTML forms. Before you send that data to the server, though, you want to make sure it’s well formed, complete, and valid. But you’d really prefer not to have to write code to test the data yourself.

Solution

Form validation is a perfect opportunity to introduce an external library. For a given form, such as the following:

    <form name="example" action="" method="post">
    <fieldset>
        <legend>Example</legend>
        <div>
            <label for="name">Name (required):</label>
            <input type="text" id="name" name="name" value="" />
        </div>
        <div>
            <label for="email">Email (required):</label>
            <input type="text" id="email" name="email" value="">
        </div>
        <div>
            <label>Website:</label>
            <input type="text" id="url" name="url" value="">
        </div>

        <div>
            <label>Credit ...

Get JavaScript Cookbook, 2nd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.