We launched a new IT training category! Check out the 140+ courses now.

Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member

Creating a generic input validation function

From: Validating and Processing Forms with JavaScript and PHP

Video: Creating a generic input validation function

In the last movie, we added dynamic validation to our form with regular expressions, so we can give the users some feedback while they're typing out in the form. So if I come over here and I try to type in something other than a telephone number. And when I hit the tab key, it says input does not match expected pattern. This works fine, but we could make it be a lot more efficient, and also easily make it work with any of our other input fields. So, let's take a look at how we can take this concept. And generalize it to work with a range of fields.

Creating a generic input validation function

In the last movie, we added dynamic validation to our form with regular expressions, so we can give the users some feedback while they're typing out in the form. So if I come over here and I try to type in something other than a telephone number. And when I hit the tab key, it says input does not match expected pattern. This works fine, but we could make it be a lot more efficient, and also easily make it work with any of our other input fields. So, let's take a look at how we can take this concept. And generalize it to work with a range of fields.

We're using a pattern for detecting phone numbers from the website html5forms.com. Matter of fact, we use the same pattern twice, once in our index.html file, you can see it if you scroll down to the telephone field that there's a pattern right here. And we're also using it in our script. And that is right here. I have to escape some of those characters in order to make it work. So we can simplify this by having JavaScript read the pattern from the input field, since once the page is loaded, the pattern becomes a property of the input field.

So we can replace all this with just the text, this.pattern. Remember that this right now happens to be related to my field. And my field is linked to my form and the telephone input field within that form. So since we're reading the pattern what we can also do is read the place holder field. So we'll create another variable, I'll just copy and paste this one. This one will be called my placeholder. And it's going to read the pattern placeholder field. Now that we have the pattern and the placeholder, we can change our text right here, so that instead of physically putting the input field's placeholder, we can just add it by adding a plus sign here and then saying, my placeholder. So if I save this and I go back into my form, I'm going to refresh the page, and try the same thing, you'll notice that it's working exactly like before, but the way we get the information is a lot different.

Now the form will be easier to update since we only have to update the placeholder field in the index.html. In the movie on looking up form elements, we discovered we can look up all the input fields at once by using the get element by tag name function. So, if we wanted to, we could use that to go through all of our input fields and run our validation code, pass them in sequence. So, I'm going to switch over to my JavaScript, and at the very top, I'm going to add a new variable called input fields.

And that's going to be equal to document, the form, and I'm going to get elements by tag name. And just get all the input fields fed into an array. So now what we need to do is find a way of executing all this code for every single one of those input fields. To do that, I'm going to use the For function. So it's going to look like this. For, then I'm going to add a key here, in input fields. And then, it's going to execute the code within these curly brackets in sequence. So we can grab all this code, cut it out of here, and just paste it right in here. Now, I'm going to go ahead and indent so it is easier to read. And I'll make sure I'll add a comment right here. And now all we need to do is modify, the my field variable, so that instead of looking for just the telephone, it's going to go through each one of these input fields.

That looks like this, I'll type input fields, and then, I'll pass it along the key, and now it's going to go through every one of those input fields in a loop, and attach an on change handler to each one of them. And in each of those, it's going to look for the pattern that is in the pattern attribute, and it's going to put the placeholder in the placeholder attribute. Let's go ahead and save that and see what happens in the form. So check here, I'm going to refresh this page. And let's test out the telephone again. Type something that's not a telephone. And it tells you that the input does not match expected pattern, that's what it was doing before. Now let's try typing in something else, like a name. So the name expects the pattern to be last name comma first, so I'll just type something in there.

Notice that now it's telling you that the input does not match expected pattern, but it's showing you a different pattern. So, you can easily use JavaScript functions like getElementByTagName, to help you take code for a single validation and turn it into code for your entire form.

Show transcript

This video is part of

Image for Validating and Processing Forms with JavaScript and PHP
 
Expand all | Collapse all
  1. 3m 36s
    1. Welcome
      1m 9s
    2. What you should know
      1m 2s
    3. Using the exercise files
      1m 25s
  2. 12m 50s
    1. Understanding forms
      2m 2s
    2. Working with form fields
      7m 4s
    3. Using the form tag
      3m 44s
  3. 19m 23s
    1. Using input validation
      2m 10s
    2. Adding required fields and placeholders
      1m 31s
    3. Constraining numeric and date fields
      2m 32s
    4. Accepting multiple entries
      1m 41s
    5. Limiting uploads by MIME types
      2m 35s
    6. Assisting text input with a datalist
      1m 55s
    7. Constraining with regular expression patterns
      6m 59s
  4. 42m 13s
    1. Accessing forms
      3m 57s
    2. Looking up form elements
      3m 35s
    3. Handling focus changes
      2m 47s
    4. Detecting the onchange event
      4m 31s
    5. Using the selectedIndex property
      2m 30s
    6. Dynamic validation with regular expressions
      7m 0s
    7. Creating a generic input validation function
      4m 31s
    8. Validating in older browsers with Modernizr
      7m 32s
    9. Interrupting form submission with onsubmit
      5m 50s
  5. 15m 20s
    1. Understanding jQuery
      3m 47s
    2. Validating on submit with jQuery
      3m 45s
    3. Building interactive jQuery validation
      2m 34s
    4. Using the jQuery Validation plugin
      5m 14s
  6. 32m 57s
    1. Communicating with PHP servers
      2m 27s
    2. Retrieving data from superglobals
      8m 18s
    3. Using server-side validation
      4m 59s
    4. Adding in-page validation
      5m 22s
    5. Mirroring input data back to the user
      7m 46s
    6. Sanitizing form input
      4m 5s
  7. 43m 29s
    1. Mailing form data
      8m 28s
    2. Understanding file uploads
      3m 1s
    3. Uploading files
      9m 20s
    4. Processing form data with AJAX
      8m 14s
    5. Preparing your database
      5m 50s
    6. Pushing data
      8m 36s
  8. 1m 17s
    1. Next steps
      1m 17s

Start learning today

Get unlimited access to all courses for just $25/month.

Become a member
Sometimes @lynda teaches me how to use a program and sometimes Lynda.com changes my life forever. @JosefShutter
@lynda lynda.com is an absolute life saver when it comes to learning todays software. Definitely recommend it! #higherlearning @Michael_Caraway
@lynda The best thing online! Your database of courses is great! To the mark and very helpful. Thanks! @ru22more
Got to create something yesterday I never thought I could do. #thanks @lynda @Ngventurella
I really do love @lynda as a learning platform. Never stop learning and developing, it’s probably our greatest gift as a species! @soundslikedavid
@lynda just subscribed to lynda.com all I can say its brilliant join now trust me @ButchSamurai
@lynda is an awesome resource. The membership is priceless if you take advantage of it. @diabetic_techie
One of the best decision I made this year. Buy a 1yr subscription to @lynda @cybercaptive
guys lynda.com (@lynda) is the best. So far I’ve learned Java, principles of OO programming, and now learning about MS project @lucasmitchell
Signed back up to @lynda dot com. I’ve missed it!! Proper geeking out right now! #timetolearn #geek @JayGodbold
Share a link to this course

What are exercise files?

Exercise files are the same files the author uses in the course. Save time by downloading the author's files instead of setting up your own files, and learn by following along with the instructor.

Can I take this course without the exercise files?

Yes! If you decide you would like the exercise files later, you can upgrade to a premium account any time.

Become a member Download sample files See plans and pricing

Please wait... please wait ...
Upgrade to get access to exercise files.

Exercise files video

How to use exercise files.

Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.


Exercise files

Exercise files video

How to use exercise files.

For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ .

This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.

Join now Already a member? Log in

Are you sure you want to mark all the videos in this course as unwatched?

This will not affect your course history, your reports, or your certificates of completion for this course.


Mark all as unwatched Cancel

Congratulations

You have completed Validating and Processing Forms with JavaScript and PHP.

Return to your organization's learning portal to continue training, or close this page.


OK
Become a member to add this course to a playlist

Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.

Get started

Already a member ?

Become a member to like this course.

Join today and get unlimited access to the entire library of video courses.

Get started

Already a member?

Exercise files

Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more

Get started

Already a Premium member?

Exercise files video

How to use exercise files.

Ask a question

Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.

Please enter the text shown below:

The classic layout automatically defaults to the latest Flash Player.

To choose a different player, hold the cursor over your name at the top right of any lynda.com page and choose Site preferences from the dropdown menu.

Continue to classic layout Stay on new layout
Exercise files

Access exercise files from a button right under the course name.

Mark videos as unwatched

Remove icons showing you already watched videos if you want to start over.

Control your viewing experience

Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.

Interactive transcripts

Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.

Are you sure you want to delete this note?

No

Your file was successfully uploaded.

Thanks for signing up.

We’ll send you a confirmation email shortly.


Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.