HTML5 and CSS3, Second Edition

(singke) #1

Tip 8


Validating User Input without JavaScript


When we build web forms, we’re trying to get data from our users and store
it or process it and turn it into useful information. Some of the data we ask
for might be required, and other bits might be optional. Sometimes that data
needs to be in a certain format, and we want to validate the data before we
store it so we can give the user a chance to make corrections. Traditionally,
developers validate user input in server-side code, because client-side valida-
tion techniques with JavaScript can be easily disabled. Server-side validation
results in a clumsy, slow user experience because users have to fill in the
fields, submit the form, and wait for the whole page to refresh to see what
they did wrong. To give quick feedback to users, developers end up writing
client-side validation with JavaScript anyway, effectively writing validation
twice. This has its own set of problems.

HTML5 introduces a couple of attributes for form elements that we can use
to validate user input on the client side, so we can catch simple input errors
before the user sends the requests to the server without writing JavaScript.

The AwesomeCo support site’s signup page is a great place for us to test out
these new attributes. Users need to provide their first name, last name, and
email address. They also need to enter a password. Let’s start by ensuring
the first name, last name, and email fields are filled in.

We require that a user fills in a form field by adding the requiredattribute to
the element just like we do with the <autofocus> attribute. So, we can add the
required attribute to the First Name, Last Name, and Email fields on the original
signup form.

html5_validation/index.html
<li>
<labelfor="first_name">FirstName</label>

<inputid="first_name"type="text"
autofocus="true"
required
name="first_name"placeholder="'John'">
</li>
<li>
<labelfor="last_name">LastName</label>

Chapter 3. Creating User-Friendly Web Forms • 54


Download from Wow! eBook <www.wowebook.com> report erratum • discuss

Free download pdf