Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Form Validation | DOM Event Handling and Forms
HTML & JavaScript Interactivity for Beginners

book
Form Validation

Form validation is crucial in web application development as you can't trust the user's input. Therefore, you need to validate the user input both on the server and client side. In this chapter, you'll practice what you have learned in the previous chapter by validating each form element one after the other before submitting the form to the server. Let's get started.

Text Input Validation using onblur

Throughout this chapter, we'll create form elements and check user input each time a user completes the input or while typing. Let's start with the form first.

html
<form action = '' method = 'post' name = 'myform' onsubmit = 'return valForm(this)'>

The above piece of code creates a form element with the action attribute and then returns true or false from the onsubmit event handler. You'll discover more on this a little later.

Then we'll create an <input> element where the user has to enter their name.

html
<form action = '' method = 'post' name = 'myform' onsubmit = 'return valForm(this)'>
<div>
<label>Full Name: </label>
<input type = 'text' name = 'fname' size = '50' onblur = 'checkName(this)'/>
<p class = 'error'></p>
</div>
<input type = 'submit' value = 'Submit'/>
</form>

After that, to make things easier for the user, the code will check if they've entered the input correctly when they move out of the textbox. Below is the JavaScript function that does it.

js
function checkName(ele) {
var regName = /\d+$/g;
errors = document.getElementsByClassName('error');
if ((ele.value == '') || (regName.test(ele.value))) {
errors[0].innerHTML = 'Please enter the name in correct format';
ele.focus();
return false;
} else {
errors[0].innerHTML = '';
return true;
}
}

The above Javascript code creates a regular expression to ensure that the user doesn't enter any numeric values or special characters. Then in the following line, it makes sure that the user doesn't leave the name field empty and that they only enter text by calling the test method (pre-defined method in the javascript library) using the regular expression you created.

If either condition is false, an error message is displayed on the paragraph tag below the name textbox . Then the focus is set to the textbox for the user to re-enter and return false.

Else will return true and clear the <error> tag's contents to ensure all is good.

Email Input Validation

Next, we'll place a textbox of type email beneath the full name textbox for the user to enter their email address. Then we'll validate it with the onchange event handler so that the user knows if they have typed the correct email address or not.

html
<div>
<label>Email Address: </label>
<input type = 'email' name = 'myemail' size = '50' onchange = 'checkEmail(this)' />
<p class = 'error'></p>
</div>

JavaScript code:

js
function checkEmail(ele) {
var regEmail = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/g;
errors = document.getElementsByClassName('error');
if ((ele.value == '') || (!regEmail.test(ele.value))) {
errors[0].innerHTML = 'Please enter the name in correct format';
ele.focus();
return false;
} else {
errors[0].innerHTML = '';
return true;
}
}

The check email function checks the validity of the email address by checking if it's empty and matches the pattern that you've specified in the regular expression. The rest will be the same as that of the name field.

Onsubmit Validation

Then in the onsubmit event handler, you must ensure that all the fields are filled correctly. If you fill them correctly, it will submit the form to the value specified in the action attribute.The form element is passed as a parameter in this instance.

js
function valForm(form) {
if ((checkName(form.fname)) && (checkEmail(form.myemail))) {
return true;
} else {
return false;
}
}
html

index.html

copy
<!DOCTYPE html>
<html>
<head></head>
<body>
<form action = '' method = 'post' name='myform' onsubmit = 'return valForm(this)'>
<div>
<label>Full Name: </label>
<input type = 'text' name = 'fname' size = '50' onblur = 'checkName(this)'/>
<p class = 'error'></p>
</div>
<div>
<label>Email Address: </label>
<input type = 'email' name = 'myemail' size = '50' onchange = 'checkEmail(this)'/>
<p class = 'error'></p>
</div>
<input type = 'submit' value = 'Submit'/>
</form>
<script type = 'text/javascript'>
function checkName(ele) {
var regName = /\d+$/g;
errors = document.getElementsByClassName('error');
if ((ele.value == '') || (regName.test(ele.value))) {
errors[0].innerHTML = 'Please enter the name in correct format';
ele.focus();
return false;
} else {
errors[0].innerHTML = '';
return true;
}
}

function checkEmail(ele) {
var regEmail = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/g;
errors = document.getElementsByClassName('error');
if ((ele.value == '') || (!regEmail.test(ele.value))) {
errors[1].innerHTML = 'Please enter the email in correct format';

Now you have an understanding of how form validation works. Likewise, you can validate any form elements using the techniques you've learned here and in the previous chapter.

1. After hitting the submit button, what does the validateForm() do?

2. Which method will be executed first when you accidentally click the submit button without filling in the textbox?

question mark

After hitting the submit button, what does the validateForm() do?

<form name = 'myForm' action = 'form-data.php' onsubmit = 'return validateForm()' method = 'post'>
Name: <input type = 'text' name = 'fname'> <input type = 'submit' value = 'Submit'>
</form>

Select the correct answer

question mark

Which method will be executed first when you accidentally click the submit button without filling in the textbox?

<form name = 'myForm' action = 'form-data.php' onsubmit = 'return validateForm()' method = 'post'>
Name: <input type = 'text' name = 'fname' onblur = cherckInput(this)> <input type = 'submit' value = 'Submit'>
</form>

Select the correct answer

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 2. Kapittel 4

Spør AI

expand
ChatGPT

Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår

We use cookies to make your experience better!
some-alt