Javascript provides the ability to extend the kinds of error-checking essential to accepting information from website visitors through HTML forms. This is essential to having validated, correctly-formatted data for subsequent website validations. This blog post covers the landscape of Javascript HTML form validation.
What Is Javascript HTML Form Validation?
Web pages are a two-way street: the website presents information to you and, from time to time, requests some from you. After you hit the ‘Submit’ button you may be presented with messages directing you to modify your entries to be accepted. These messages include:
website message | meaning |
---|---|
Enter a valid email address | the data appears not to be an email address |
Enter your phone number in the format xxx-xxx-xxxx | a specific data format is required for a phone number |
Enter a password between 8 and 30 characters long, containing one uppercase letter, one symbol, and one number | a very specific, custom data format is required |
This field is required | a non-blank value is needed |
These are all examples of HTML form validation.
Types of Javascript HTML Form Validation
There are two types of form validation:
Client-side validation — done locally (on your device) within the web browser
Server-side validation — in some way more comprehensive than can be done locally, requiring your information sent to the web server that’s also sharing the web page content
Whichever method(s) are needed to validate the form data, once done the information is accepted it will be used; either immediately or saved for future use in a database on the web server. If there are validation issues you will be presented a message explaining the issue and given a chance to modify your form input appropriately.
Why Validate Form Input Data?
Validation slows down the process of getting user-submitted information into the system, something which intuitively suggests that it might better be omitted. This is staggeringly wrong for a variety of reasons:
We need the data in a format which can be used. User input that’s incorrect (like an email address missing the domain part) or deficient (like a phone number without the area code) breaks subsequent operations which require correct data. The same goes for data that is omitted when required.
We need to protect the system from malicious input by bad actors, lest the integrity of back-end database or the safe operation of web applications be compromised. (See the related blog entry on how databases defeat SQL injection attacks.
We need to protect user data and accounts, so we use form validation to ensure passwords are secure (as defined by some company policy).
HTML Input Attributes Can Constrain Values
HTML form elements have attributes which may be used to constrain input values to valid values. In the list below, pay particular attention to the disabled
, min
, max
, pattern
, required
, and type
attributes.
Note that input restrictions aren’t foolproof. Consider additional server-side validation.
attribute | usage |
---|---|
autocomplete | enables autocomplete; works with form , text , search , url , tel , email , password , range , color , and date pickers |
autofocus | an input field should get focus after the page loads |
disabled | an input field is disabled; its value will not be sent when submitting the form |
height , width | size of an input element |
list | provides pre-defined options for input |
maxlength | the maximum number of characters accepted in an input field |
min , max | the minimum and maximum values for a number , range , date , datetime-local , month , time , week input field; use both together to create a legal values range |
multiple | allow one or more values to be input; works with email , file |
pattern | a regular expression that must be matched; works with date , search , text , url , tel , email , password |
placeholder | a short hint text that describes the expected input; works with text , search , url , tel , email , password |
readonly | an input field is read-only; its value will be sent when submitting the form |
required | the input field must be filled out; works with text , search , url , tel , email , password , number , checkbox , radio , file , and date pickers |
size | the character width of the input field |
step | permitted number intervals for an input field, used with min and max ; works with number , range , date , datetime-local , month , time , week |
value | an initial value for an input field |
CSS Pseudo Selectors Can Constrain Values
Similarly, the following CSS pseudo-selectors can constrain input values: :disabled
, :invalid
, :optional
, :required
, :valid
Putting It All Together
Javascript HTML form validation requires two components: the HTML form that accepts inputs (constrained as specified above) and a Javascript function which performs validation above the built-in constraints.
An HTML Login Credentials Input Form
The following is an exceedingly simple HTML login credentials input form. Items to note:
- the form name,
loginCredentialsForm
, is used by the Javascript function - the Javascript function must be in an existing script file specified by the
action
directive - the HTML form field names are used by the Javascript function
<form name="loginCredentialsForm"
action="/loginValidation.php"
onsubmit="return validateCredentialsForm()"
method="post">
Username: <input type="text" name="user">
Password: <input type="text" name="pass">
<input type="submit" value="Submit">
</form>
This input form can be beefed up considerably with the HTML input attributes listed above, minimizing the work needed to be done by the following Javascript validation function. (Using built-in input attributes to constrain values also minimizes the attack vector exposure that comes along with using custom code written by a local programmer. Use the community’s work to your best advantage.)
A Javascript Validation Function
Following is the corresponding Javascript validation function:
function validateCredentialsForm() {
let user = document.forms["loginCredentialsForm"]["user"].value;
if (user == "") {
alert("Username is required; retry.");
return false;
}
// additional form element validation goes here
}
Conclusion
This blog post provided an introduction to Javascript HTML form validation, the input attributes which help constrain user data to valid, useful values, and provided a bare-bones input validation scheme (the HTML form and the Javascript validation script).
To learn more about Javascript, check out other Javascript blog posts and enroll in our Javascript Nanodegree programs, including Intermediate Javascript.