Can javascript handle form validations?
Before submitting data to the
server, it is important to ensure all required form controls are filled out, in the correct format. This is called client-side form validation, and helps ensure data submitted matches the requirements set forth in the various form controls. This article leads you through basic concepts and examples of client-side form validation. Client-side validation is an initial check and an important feature of good user experience; by catching invalid data on the client-side, the
user can fix it straight away. If it gets to the server and is then rejected, a noticeable delay is caused by a round trip to the server and then back to the client-side to tell the user to fix their data. However, client-side validation should not be considered an exhaustive security measure! Your apps should always perform security checks on any form-submitted data on the server-side as well as the client-side, because client-side validation is too
easy to bypass, so malicious users can still easily send bad data through to your server. Read Website security for an idea of what could happen; implementing server-side validation is somewhat beyond the scope of this module, but you should bear it in mind. Go to any popular site with a registration form, and you will notice that they provide feedback when you don't enter your data in the format they are expecting. You'll get messages such as: This is called form validation. When you enter data, the browser and/or the web server will check to
see that the data is in the correct format and within the constraints set by the application. Validation done in the browser is called client-side validation, while validation done on the server is called server-side validation. In this chapter we are focusing on client-side validation. If the information is correctly formatted, the application allows the data to be submitted to the server and (usually) saved in a database; if the information isn't
correctly formatted, it gives the user an error message explaining what needs to be corrected, and lets them try again. We want to make filling out web forms as easy as possible. So why do we insist on validating our forms? There are three main reasons: Warning: Never trust data passed to your server from the
client. Even if your form is validating correctly and preventing malformed input on the client-side, a malicious user can still alter the network request. Different types of client-side validationThere are two different types of client-side validation that you'll encounter on the web:
Using built-in form validationOne of the most significant features of modern form controls is the ability to validate most user data without relying on JavaScript. This is done by using validation attributes on form elements. We've seen many of these earlier in the course, but to recap:
If the data entered in a form field follows all of the rules specified by the above attributes, it is considered valid. If not, it is considered invalid. When an element is valid, the following things are true:
When an element is invalid, the following things are true:
Built-in form validation examplesIn this section, we'll test out some of the attributes that we discussed above. Simple start file Let's start with a simple example: an input that allows you to choose whether you prefer a banana or a cherry. This example involves a simple text
To begin, make a copy of The required attribute The simplest HTML
validation feature is the Add a
Note the CSS that is included in the example file:
This CSS causes the input to have a red dashed border when it is invalid and a more subtle solid black border when valid. We also added a background gradient when the input is required and invalid. Try out the new behavior in the example below: Try submitting the form without a value. Note how the invalid input gets focus, a default error message ("Please fill out this field") appears, and the form is prevented from being sent. The presence of the Note: For good user experience, indicate to the user when form fields are required. It isn't only good user experience, it is required by WCAG accessibility guidelines. Also, only require users to input data you actually need: For example, why do you really need to know someone's gender or title? Validating against a regular expression Another useful validation feature is the Regexps are quite complex, and we don't intend to teach you them exhaustively in this article. Below are some examples to give you a basic idea of how they work.
There are many more possibilities that we don't cover here. For a complete list and many examples, consult our Regular expressions documentation. Let's implement an example. Update your HTML to add a
This gives us the following update — try it out: In this example, the At this point, try changing the value inside the If a non-empty value of the Note: Some
Constraining the length of your entries You can constrain the character length of all text fields created by Browsers often don't let the user type
a longer value than expected into text fields. A better user experience than just using Constraining the values of your entries For number fields (i.e. Let's look at another example. Create a new copy of the fruit-start.html file. Now delete the contents of the
Here is the example running live: Note: Full exampleHere is a full example to show usage of HTML's built-in validation features. First, some HTML:
And now some CSS to style the HTML:
This renders as follows: See Validation-related attributes for a complete list of attributes that can be used to constrain input values and the input types that support them. Validating forms using JavaScriptYou must use JavaScript if you want to take control over the look and feel of native error messages. In this section we will look at the different ways to do this. The Constraint Validation APIMost browsers support the Constraint Validation API, which consists of a set of methods and properties available on the following form element DOM interfaces:
The Constraint validation API makes the following properties available on the above elements.
The Constraint Validation API also makes the following methods available on the above elements and the
Implementing a customized error messageAs you saw in the HTML validation constraint examples earlier, each time a user tries to submit an invalid form, the browser displays an error message. The way this message is displayed depends on the browser. These automated messages have two drawbacks:
Customizing these error messages is one of the most common use cases of the constraint validation API. Let's work through a simple example of how to do this. We'll start with some simple HTML (feel free to put this in a blank HTML file; use a fresh copy of fruit-start.html as a basis, if you like):
And add the following JavaScript to the page:
Here we store a reference to the email input, then add an event listener to it that runs the contained code each time the value inside the input is changed. Inside the contained code, we check whether the email input's
If the You can try it out below: A more detailed exampleNow that we've seen a really simple example, let's see how we can use this API to build some slightly more complex custom validation. First, the HTML. Again, feel free to build this along with us:
This simple form uses the Our input
to validate is an We are aiming to show the error messages inside a Note: A key point here is that setting the Now onto some basic CSS to improve the look of the form slightly, and provide some visual feedback when the input data is invalid:
Now let's look at the JavaScript that implements the custom error validation.
The comments explain things pretty well, but briefly:
Here is the live result: The constraint validation API gives you a powerful tool to handle form validation, letting you have enormous control over the user interface above and beyond what you can do with HTML and CSS alone. Validating forms without a built-in APIIn some cases, such as custom controls, you won't be able to or won't want to use the Constraint Validation API. You're still able to use JavaScript to validate your form, but you'll just have to write your own. To validate a form, ask yourself a few questions: What kind of validation should I perform?You need to determine how to validate your data: string operations, type conversion, regular expressions, and so on. It's up to you. What should I do if the form doesn't validate?This is clearly a UI matter. You have to decide how the form will behave. Does the form send the data anyway? Should you highlight the fields that are in error? Should you display error messages? How can I help the user to correct invalid data?In order to reduce the user's frustration, it's very important to provide as much helpful information as possible in order to guide them in correcting their inputs. You should offer up-front suggestions so they know what's expected, as well as clear error messages. If you want to dig into form validation UI requirements, here are some useful articles you should read:
An example that doesn't use the constraint validation APIIn order to illustrate this, the following is a simplified version of the previous example without the Constraint Validation API. The HTML is almost the same; we just removed the HTML validation features.
Similarly, the CSS doesn't need to change very much; we've just turned the
The big changes are in the JavaScript code, which needs to do much more heavy lifting.
The result looks like this: As you can see, it's not that hard to build a validation system on your own. The difficult part is to make it generic enough to use both cross-platform and on any form you might create. There are many libraries available to perform form validation, such as Validate.js. Test your skills!You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on — see Test your skills: Form validation. SummaryClient-side form validation sometimes requires JavaScript if you want to customize styling and error messages, but it always requires you to think carefully about the user. Always remember to help your users correct the data they provide. To that end, be sure to:
Once you have checked that the form is filled out correctly, the form can be submitted. We'll cover sending form data next.
In this moduleAdvanced TopicsWhich JavaScript event is useful for form validation?Notice that for validation, the JavaScript function containing the code to validate is called on the onSubmit event of the form.
Which language is used for form validation?Basically, if validation requires comparison to database values - use PHP. If it doesn't - use Javascript. P.S. Anyone can take JS code from your website, because it is public.
Does JavaScript validate user input?Validating form input with JavaScript is easy to do and can save a lot of unnecessary calls to the server. It can prevent people from leaving fields blank, from entering too little or too much or from using invalid characters. User-submitted data should also always be verified using a secure server-side script.
Can we validate clientDifferent types of client-side validation
Built-in form validation has better performance than JavaScript, but it is not as customizable as JavaScript validation. JavaScript validation is coded using JavaScript. This validation is completely customizable, but you need to create it all (or use a library).
|