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

Dynamic validation with regular expressions

From: Validating and Processing Forms with JavaScript and PHP

Video: Dynamic validation with regular expressions

Regular expressions give you a way to search for patterns in form fields. And that can help with validation and processing. I talked about regular expressions in the movie on constraining with regular expression patterns. The regular expression syntax in HTML5 is pretty similar to JavaScript. As a matter of fact, the HTML5 implementation is a copy of the JavaScript implementation, so you can use them mostly interchangeably. In JavaScript, you have to create a regular expression pattern and then use the search method to search for that pattern in an input field. So, you might be asking yourself, why do I need to validate for patterns, if I can just use the pattern attribute in HTML5.

Dynamic validation with regular expressions

Regular expressions give you a way to search for patterns in form fields. And that can help with validation and processing. I talked about regular expressions in the movie on constraining with regular expression patterns. The regular expression syntax in HTML5 is pretty similar to JavaScript. As a matter of fact, the HTML5 implementation is a copy of the JavaScript implementation, so you can use them mostly interchangeably. In JavaScript, you have to create a regular expression pattern and then use the search method to search for that pattern in an input field. So, you might be asking yourself, why do I need to validate for patterns, if I can just use the pattern attribute in HTML5.

Well, with validation, it's important to try to be as compatible with older browsers as possible. Using regular expressions in JavaScript, will let you build validation that's compatible with older browsers. Another reason is that the pattern attribute, prevents the form from submitting but it doesn't offer the user feedback while they're filling out the form. So, it's more user friendly and helpful to give the user feedback as they're filling out fields, rather then waiting until they consider the task already done. So, we're going to work with this form and we're going to build validation that happens, as soon as a user types something into this telephone field.

So, I'm going to go to the code and I'm going to use a separate JavaScript file. I've already created the file right here, but I need to link to it from my index.html document. I also have an error field with an ID of form error, on this HTML page. So, I'm going to go all the way to the bottom, and right before the closing body tag I'm going to make a script tag that links to our JavaScript. Now that this too are linked, I'll switch over to my JavaScript file, and I'll start by creating a couple of variables that will target the telephone attribute. Then I'm going to create a variable for the error, so that targets the error field.

Next we're going to need a pattern, and I'm going to get that form this website called html5pattern.com. Html5pattern.com has a lot of different HTML5 type patterns and since they're very compatible with JavaScript patterns, we're going to use it to build our application. So, I'm going to come here and go to the phone section. And scroll down to the USA phone number and just grab this telephone number right here. And I'll switch back into my script. Now this is the pattern that I'm already using in the phone field. So, really I could have grabbed it from right here. But I wanted to show you the website.

And let's take a look at the telephone field. You can see that I've already used that pattern. Right here. So, I'm going to put that into my script. Before I can use it, though, I need to escape some of these digit fields. The search function expects a pattern as a string. So, if we submit the pattern like this, it's not going to work. We're going to need to add slashes to everything that already has a slash in this pattern. Now we can start creating the onchange function. So, I'm targeting myField, which is targeting the document.theform.telephone.

And I'm going to add an onchange handler, that will look for that event, as soon as it happens. So, now I'm going to create a variable for the pattern, and I'm going to set that variable to be a new regular expression. And into that regular expression, I'm going to pass my pattern. So, I'm going to grab it from right here, and go to my regular expression, and in quotes, paste the pattern in. And then I'm going to add a comma and then the keyword i, which just means that this search will be a case insensitive search.

Doesn't necessarily matter for phones, but it's a good thing to have for any kind of pattern so we'll leave it like that. Now, I'm going to create a variable and it's going to be called isValid. And that value is going to implement the search function. So, what we want to do is search for this, this is going to be myField, it's going to be the same as myField. So, I'm going to ask the myField value to execute the search function and into that I'm going to pass the pattern that I just created, myPattern. And I'm going to check to see if this pattern is greater than or equal to zero. The reason for that is that, search will look for the pattern in some text, in this case it's going to look for the pattern inside this value, which is the myField value, which is targeting this telephone.

And if the pattern is found within the text, then it's going to return a numerical value of where that value was found in the text. If it doesn't find the pattern, it's going to return negative one. So, what I need to do is check to make sure that, that pattern is greater than or equal to 0. That means the pattern has been found. The JavaScript search function checks for a pattern in a string. It returns the position of the pattern within the string. If the pattern doesn't exist, it's going to return a negative one.

So, if the pattern matches then we can output something to the screen. So now I'm going to do a check for, is the pattern not valid, right, so that's what this says right here. Is the pattern valid? And if it's not valid, then we're going to do something and if it is valid we're going to do something else. So, just sort of we can remember pattern not valid, adding a comment here, so pattern is valid.

And what we'll do is, we'll target the field myError which right now it's pointing to the element with an ID form error. And we'll get the inner HTML of that field, and then make it equal to some text. INput does not match expected pattern. And we'll put in the pattern that we expect here so the user can read it. Now, if the pattern is valid, then it's just going to clear out this field. We'll just make it blank like this.

And then, I'm going to save this file. I could probably use another comment right here. One more thing I have to do is, I have to make sure that this IF part is actually within the onchange handler. So, I'm going to go and put that in here. Let me space it out a little better as well. Tab it in, and now it'll do this validation check after the field has changed. So, I'm going to save this and switch back over to my browser. Make sure I refresh my page. And if I go to the phone field and try to type something other than a phone. Notice that I get "the input that not's match expected pattern text" that I typed in there.

If I do type a phone, type in something in the correct format and I hit tab, that goes away. So, now that we're able to give feedback to the user not just on submit, but also during completion, it seems like the form is a little more user-friendly and helpful. There's a few ways we could probably improve on the script and make it more generic so that we can use it in other input fields. We'll tackle that on the next movie.

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 preferencesfrom 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.