Header Ads Widget

Validation of form elements by constraints and JavaScript

 In the previous two posts, we saw what are the input elements and how to create a form. 

In this post, we will see form validation, Different validation methods. 

Before applying validation to form elements, let discussing on what validation is and why it is necessary. 

What is validation? 

When you go to any website, you can see the forms like register, login, and contact forms. If you enter a wrong value or remain blank in the input field then a popup box or alert message will display to give you a warning about wrong data. This is called the validation of input fields.

For example, 

If you enter a text value in a number field, you get a message like “Please enter valid input”.

Why Validation is necessary? 

Validation is necessary for the authenticity of a user. Validation restricts the false or blank input. Validation is mainly needed for privacy. The form design is incomplete without validation. 

What validation includes? 

Validation includes checking an empty field, and the correctness and accuracy of input data. 

Types of validation

Validation is applied using different ways like methods, constraints, etc... 

Validation is divided into two types. 

(1) Client-side validation:-

Client-side validation is done by the browser at time of data input. 

(2) Server-side validation:-

Server-side validation is done by the server after data is submitted to the server. 
 This post will describe the client-side validation in detail. 

Client-side validation

What is client-side validation? 

Before submitting the form data web browser checks whether all input fields are filled or not and if filled then verifies that inputted data are accurate. 
This validation is called client-side validation.
Client-side validation is performed automatically by the browser. It gives a user-friendly experience. 
Client-side-validation is categorized into two parts:
(1) Validation using HTML5 Constraints
(2) JavaScript Validation

(1) Validation using HTML5 constraints

The concept of constraint validation was introduced in HTML 5. Constraints validation applies to input fields such as text field, number field, date, email, password, etc... 
HTML5 Constraints validation includes:

HTML5 attributes

HTML 5  adds some new attributes that are used to verify user data. All attributes we have seen in the previous post, so I describe how they work as a validator. 

(1) required attribute 

The input element having the required attribute should not be empty. If you want some input field that must be filled out then set the required attribute to input control. 

Example:-
HTML5 required attribute
HTML5 required attribute 

(2) type attribute 

The type attribute such as number, and email accept only data according to type. 

Example:-
HTML5 type attribute
HTML 5 type attribute 

(3) max and min attributes 

The max and min attributes restrict user input for a numeric field. 

Example:-
HTML5 min and max attribute
HTML5 min and max attribute 


(4) maxlength and minlength attributes 

The minlength and maxlength attributes are used to limit a string value. 

Example:-
HTML5 minlength and maxlength attributes
HTML5 minlength and maxlength attributes 

(5) pattern attribute 

The pattern attribute specifies a group of characters in a specific pattern.
The user must have to input data in a specified pattern in the input field. 
To define patterns regular expressions are used. 
Which types of characters are used in a regular expression? 
Alphabets (A-Z, a-z), Numbers (0-9), Brackets ([], {}), Slashes(/, \), astreak(*), etc... 

Example:-
HTML5 pattern attribute
HTML5 pattern attribute 

(6) disabled attribute 

The user has nothing to do with the disabled attribute. Disabled field display in gray color. 

Example:-
HTML5 disabled attribute
HTML5 disabled attribute
 
Note:- Code is given below. (HTML code) 

CSS pseudo selectors

As HTML5  introduced some new attributes for validation CSS3 adds pseudo selectors to give the user a visual clue about input data. 
CSS pseudo selectors have used conjunction with input attributes. 
Following are pseudo selectors that are used as validation alerts for a user by changing CSS styles. 

(1) :required pseudo selector

:required pseudo selector selects those input fields that have the required attribute specified. 

(2) :valid pseudo selector

:valid pseudo selector selects those input fields which have valid input data.

(3) :invalid pseudo selector

:invalid pseudo selector selects those input fields which have invalid data entry. 

(4) :disabled pseudo selector

:disabled pseudo selector selects disable input field. 

(5) :optional pseudo selector

:optional pseudo selector selects those input field that doesn’t need to enter data compulsory. 

The following example gives you a better understanding. 

HTML code:-


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<!Doctype html>
<html>
<head>
<title>Validation</title>
<link rel="stylesheet"  href="/storage/emulated/0/Blog/selcetorvalid.css">
<style>
form{
background-color:#333;
color:#fff;
margin:300px;
padding:10px;
display:inline-block;
border:5px solid #0cc;}
label,input,textarea{
margin:10px;}
</style>
</head>
<body>

<form name="frm" action="#" method="post">
<h2>User registration form</h2>
<label for="name">Name:</label><br>
<input type="text" name="uname" required><br>
<label for="dob">Birthdate:</label><br>
<input type="date" name="dob"><br>
<label for="age">Age:</label><br>
<input type="number" name="age" min="18" max="60"><br>
<label for="phno">Phone:</label><br>
<input type="tel" name="phno" pattern="[0-9]{4}-[0-9]{2}-[0-9]{4}"><br>
<label for="addrs">Address:</label><br>
<textarea disabled></textarea><br>
<label for="eml">Email id:</label><br>
<input type="email" name="eml"><br>
<label for="pass">Password:</label><br>
<input type="password" name="pass" minlength="8"><br>
<label for="repass">Re-type password:</label><br>
<input type="password" name="repass" minlength="8"><br>
<input type="submit" >
</form>
</body>
</html>

CSS:-

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
input[type="text"]:required{
border:2px solid #00f;
background-color:#fcc;}
input[type="number"],[type="tel"],[type="email"],[type="password"]:valid{
border:2px solid #0f0;}
input:invalid{
border:2px solid #f00;}
input[type="date"]:optional{
border:2px solid #fff;}
textarea:disabled{
background-color:#ccf;}

Output:-
CSS pseudo selectors validation output
CSS pseudo selectors validation 

DOM properties and methods

You can also use DOM properties and methods for validation which is called JavaScript or constraints validation API. 

✏ DOM methods

checkValidity() 

Return true if the input field has valid data otherwise, return false for incorrect input. 

setCustomValidity() 

Set validationMessage property to an input element. 

✏ DOM properties

validity

validity property contains a set of validity properties related to an input element.

 Following are the validity properties. 

(1) customError

Returns true if customValidity message is set. 

(2) patternMismatch

Returns true if user input doesn’t match the specified pattern. False otherwise. 

(3) stepMismatch

Returns true if the input value does not follow the step attribute value. 

(4) typeMismatch

Returns true if inputted data does not match its type attribute's value. 

(5) rangeOverflow

Returns true if user input crosses the maximum limit set in the max attribute of the input element. 

(6) RangeUnderflow

Returns true if user input is smaller than the min attribute value of the input element. 

(7) tooLong

Returns true if user input exceeds the limit of the maxlength attribute value. 

(8) valid

Returns true if user input is correct. 

(9) ValueMissing

Returns true if the input element is null and set to the required attribute. 

validationMessage

Display a message about validation constraints by browser (If an input is incorrect). 

willValidate

Returns true input element will be validated when the form is submitted. Otherwise, return false. 

Example:-


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<!Doctype html>
<html>
<head>
<title>Validation using DOM</title>
<style>
form{
margin:300px;
background-color:#fc9;
padding:30px;}
</style>
</head>
<body>
<form>
<label for="nm">Enter your name:-</label><br><br>
<input type="text" id="nam" name="nm" pattern="[A-Z,a-z]"><br><br>
<input type="submit" name="sub" onclick="namecheck()">
<h2 id="i1"></h2>
</form>
<script>
function namecheck(){
const n=document.getElementById("nam");
    if(!n.checkValidity()){
     document.getElementById("i1").innerHTML=n.validationMessage;}
}
</script>
</body>
</html>

Output:-
checkValidity () with dom property
checkValidity() method 

(2)  JavaScript Validation

In JavaScript validation, the whole validation is codded in JavaScript. This validation is used function for validation. It’s called custom validation. 

Example:-


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<!Doctype html>
<html>
<head>
<title>form validation</title>
</head>
<body bgcolor="pink">
<h2>Student Attandance Form</h2>
<form name="studattand" method"post">
<label for="snmae">Stud_name:</label><br>
<input type="text" name="sname"><br><br>
<label for="rno">Roll_no:</label><br>
<input type="number" name="rno"><br><br>
<label for="attan">Attandance:</label><br>
<input type="number" name="attan"><br><br>
<button type="submit" onclick="autovalid()">Input</button>
</form>
  <script>
     function autovalid(){
     var a=document.forms["studattand"]["sname"].value;
     var b=document.forms["studattand"]["rno","attan"].value;
     if(!isNaN(a)){
    alert("Please Enter text.");
     }
    else if(b==""){
     alert("Please enter value..")
     }
     else{
     alert("Data successfully submited");
}
}
  </script>
</body>
</html>

Output:-
JavaScript validation
JavaScript validation 

Conclusion:

Client-side-validation perform in 4 ways (1) HTML 5 attributes (2) CSS3 pseudo selectors (3) DOM methods and properties (4) JavaScript code
Web developers generally use constraints validation rather than custom validation in client-side validation. HTML 5 constraints are helping the user and are easy for developers. 

Post a Comment

0 Comments