Ready to watch this entire course?
Become a member and get unlimited access to the entire skills library of over 4,900 courses, including more Developer and personalized recommendations.Start Your Free Trial Now
- View Offline
- Understanding forms
- Adding required fields and placeholders
- Accepting multiple entries
- Limiting uploads
- Handling focus changes
- Validating with regular expressions
- Working with older browsers
- Building jQuery validation
- Using server-side validation
- Sanitizing form input
- Uploading files
- Sending form data to a database
Skill Level Intermediate
In the previous movie, we created validation when the user submits the form. Now I'm going to show you how to handle more interactive validation. This time we're going to check for validation when the user exits a field and has a placeholder attribute. So I'm going to come right here and I'm going to do the dollar sign again. And I'm going to type in input. And then use the type selector which are these brackets and type in place holder that way we'll look for fields that are input fields and also have a place holder. And then we'll attach the blur method. The blur method will happen when somebody exits a field. So this will execute a function.
We'll see if it's a positive number. If it's a negative number, then the pattern hasn't been matched, so we'll check for that in an if statement. So if the pattern is not valid, then I'm going to execute some code right here. And that code will be to insert some HTML displaying the error right after the current field, so sort of like what we did up here. So I'll copy that code and change this text. Now, if it's not valid, we can also do one more thing. I'm going to move the insertion point to the field that doesn't match the current pattern.
Let's also add some comments. Now I'm going to Save this and I'll go back into my form. I'll refresh the page and I'll try to type something that doesn't match the pattern. Notice that its telling me that the entry does not match the expected pattern. And it reads the pattern value. And it won't let me go to another field until the pattern's correct. Same thing with the telephone number. Once again, our script is a lot shorter when we use the jquery library. As a byproduct, it's also more compatible. For example, older browsers support HTML attributes like pattern and placeholder inconsistently.
Although it has a lot of other benefits, adding a library to your projects is going to increase the file size of your page's download. So, when using Jquery, you'll have to weigh whether the added features warrant the slightly larger download size for your users.