Hello guys, today I will write an article about my lightweight native form validation library. Form validation is the very basic things to handle form in frontend. But why I create this form validation library?

Thousands form validation libraries

You must already known that there is thousands form validation libraries is already exists out there. But I can’t use it because most of them is too bloated for a small project.

Basic of Form Validation

Basic of Form Validation is only three :

  1. Value Validation
    Must able to validate from value.

  2. Event Validation
    Must able validate the value from event.

  3. Custom Validation
    Must able validate with custom validation rules.

Yes, only that. We actualy doen’t need more features. If you add features more than this, honestly, it’s too bloated bro.

Journey

After take a journey to searching and reading many form validation javascript out there. I failed to find form validation which is in size under 1Kb. Many lightweight form validation says that they’re are most lightweight, but actualy after minified and gzipped, it size still around 3Kb. This size is too big for me, because there are many features that actualy we don’t need it.

Without library

There is many ways to validate your html form. Actualy you are able to do validation directly without libraries. Yes this is right, but when you are working in a team, you will need a standard and if you have many different form with their own rules, your rules must be clean and easy to read. So that is why you still need a library even just for validate your form html.

Example to validate form (Pure JavaScript)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!DOCTYPE html>
<html>
<head>
<script>
function validate() {
var x = document.forms["example_Form"]["field_name"].value;
if (x == "") {
alert("Field Name is required to fill!");
return false;
}
}
</script>
</head>
<body>

<form name="example_Form" onclick="return validate()">
Field Name: <input type="text" name="field_name">
<button type="button">Submit</button>
</form>

</body>
</html>

Above example is for validate single form. If you have more than 10 fields with different rules, you will need a library so that your code will be clean and easier to read.

Introduction

Finally, I created my own library called native-form-validation. This is the very thin and lightweight of form validation library. After minified and gzipped, my library size around 1Kb only.

API

native-form-validation has only 4 features, it is :

  • form.rules(options) - Set the rules for validation.
  • form.validate(callback) - Make validation.
  • form.isValid() - Determine if validation has valid or not.
  • form.element(id) - Make validation for single element.

And for options in form.rules() is :

  • element {object} : Create rules for element. If you want to set rules for username see above example.
  • required {bool} : Make sure the input is not empty. Default is false. [optional]
  • trim {bool} : Sanitize space and whitespace on first and tail. Default is true. [optional]
  • message {string} : Customize the error text message. [optional]
  • minLength {int} : Make sure the input has {minLength} of chars. [optional]
  • maxLength {int} : Make sure the input not more than {maxLength} of chars. [optional]
  • errorPlace {string} : Display the error text into spesific element. [optional]
  • errorAddClass {object} : Add custom error class into element. [optional]
  • regex {regex} : Create validation based on regex. See this example. [optional]
  • method {function} : Create custom validation without regex. See this example. [optional]

I’ve just copied this from Wiki in my repository at here. For more detail explanation is already exists at there.

Example How To Use

I’ve upload my native-form-validation in NPM. In this case, I will create simple form login validation with Bootstrap 4. Wait? Bootsrap 4 is too big, right?I know, but most people is using Bootstrap 4 today, so I use this only in this tutorial. My small project actualy use mincss.com framework. Mincss framework is the very small css framework that I found. It size only around 1Kb.

So here is how to use this library.

1. Use with CDN

For fast and small project, we must use library with CDN to avoid cookie traffic from same domain.
Just paste this line below before tags </body> of html.

1
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/formvalidation.min.js"></script>

2. Create validation logic

In form login, there is only 3 validation, it is :

  • Username
  • Password
  • remember me (not required)

But in this tutorial I will change remember me to must check this so that it will become mandatory. So that this will giving you an example how to use this library for checkbox.

I will write the validation logic included with explanation in code.
Note: You can just copy paste this code below in new <script></script> tags.

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
42
43
44
45
46
47
48
49
50
51
var FV = new FormValidation();
FV.rules({
password: { // this is the element id "password"
required: true, // make this input required
message: 'Password must be min 3-20 chars!', // this is your error message to appear
minLength:3, // set the minlength of required char
maxLength:20, // set the maxlength of required char
errorPlace:'password-error', // put the error message to element id "password-error"
errorAddClass: { // add new class for error message element
password_group:'has-danger', // add new class "has-danger" into element id "password-group"
password:'is-invalid' // add new class "is-invalid" into element id "password"
}
},
email: { // this is the element id "email"
required:true,
// example using regex
regex: /^(([^<>()[\]\\.,;:\[email protected]\"]+(\.[^<>()[\]\\.,;:\[email protected]\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
errorPlace:'email-error',
errorAddClass: {
email_group:'has-danger',
email:'is-invalid'
}
},
checkbox: { // this is the element id "checkbox"
message: 'You have to check this first!',
// example using method for custom validation
method: function(element) { // element is the current field
return element.checked;
},
errorPlace:'checkbox-error',
errorAddClass: {
checkbox_group:'has-danger',
checkbox:'is-invalid'
}
}
});

// validate by event (optional)
document.getElementById("email").addEventListener("blur", function(){
FV.element('email').validate(); // validate for single element id "email"
});

document.getElementById("password").addEventListener("blur", function(){
FV.element('password').validate(); // validate for single element id "password"
});

document.getElementById("submit_login").addEventListener("click", function(){
if(FV.validate().isValid()) { // validate for all element is valid or not
alert('validate success!');
}
});

3. Create index.html

Create your first index.html then combine with validation logic code above.
Here is the html script before combined with validation logic above.

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 lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap 4 CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<title>Form Login</title>
</head>
<body>
<h1>Form Login</h1>
<form>

<div id="email_group" class="form-group">
<label for="email">Email address</label>
<input id="email" type="email" class="form-control" aria-describedby="emailHelp" placeholder="Enter email">
<small id="email-error" class="form-text text-danger"></small>
</div>

<div id="password_group" class="form-group">
<label for="password">Password</label>
<input id="password" type="password" class="form-control" placeholder="Password">
<small id="password-error" class="form-text text-danger"></small>
</div>

<div id="checkbox_group" class="form-check">
<input id="checkbox" type="checkbox" class="form-check-input">
<label class="form-check-label" for="exampleCheck1">Check me out</label>
<small id="checkbox-error" class="form-text text-danger"></small>
</div>

<button id="submit_login" type="button" class="btn btn-primary">Login</button>
</form>

<!-- Bootstrap 4 JS -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<!-- this is the native-form-validation library -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/formvalidation.min.js"></script>
</body>
</html>

After combined with validation logic, your full html script must look like this.

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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap 4 CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<title>Form Login</title>
</head>
<body>
<h1>Form Login</h1>
<form>

<div id="email_group" class="form-group">
<label for="email">Email address</label>
<input id="email" type="email" class="form-control" aria-describedby="emailHelp" placeholder="Enter email">
<small id="email-error" class="form-text text-danger"></small>
</div>

<div id="password_group" class="form-group">
<label for="password">Password</label>
<input id="password" type="password" class="form-control" placeholder="Password">
<small id="password-error" class="form-text text-danger"></small>
</div>

<div id="checkbox_group" class="form-check">
<input id="checkbox" type="checkbox" class="form-check-input">
<label class="form-check-label" for="exampleCheck1">Check me out</label>
<small id="checkbox-error" class="form-text text-danger"></small>
</div>

<button id="submit_login" type="button" class="btn btn-primary">Login</button>
</form>

<!-- Bootstrap 4 JS -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<!-- this is the native-form-validation library -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/formvalidation.min.js"></script>
<script>
var FV = new FormValidation();
FV.rules({
password: {
required: true,
message: 'Password must be min 3-20 chars!',
minLength:3,
maxLength:20,
errorPlace:'password-error',
errorAddClass: {
password_group:'has-danger',
password:'is-invalid'
}
},
email: {
required:true,
regex: /^(([^<>()[\]\\.,;:\[email protected]\"]+(\.[^<>()[\]\\.,;:\[email protected]\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
errorPlace:'email-error',
errorAddClass: {
email_group:'has-danger',
email:'is-invalid'
}
},
checkbox: {
message: 'You have to check this first!',
method: function(element) {
return element.checked;
},
errorPlace:'checkbox-error',
errorAddClass: {
checkbox_group:'has-danger',
checkbox:'is-invalid'
}
}
});

// validate by event (optional)
document.getElementById("email").addEventListener("blur", function(){
FV.element('email').validate();
});

document.getElementById("password").addEventListener("blur", function(){
FV.element('password').validate();
});

document.getElementById("submit_login").addEventListener("click", function(){
if(FV.validate().isValid()) {
alert('validate success!');
}
});
</script>
</body>
</html>

4. Done

Actualy, this example is similar with live example in repository, the difference is, this example here is not using jQuery. this example is pure vanilla javascript.

I’ve put this example to jsfiddle here. So that you are able to fork this directly and learning more by yourself.

Conclusion

This native-form-validation library is very small and fast, because I write this with pure javascript. You are able to use this library in any kind of javascript framework.

Why you must use this library :

  • Ligthweight size only 1Kb
    This is fast, small and very lightweight form validation library with critical features only.

  • There is no hidden or silent magic submit in this library
    Just write basic form html without any spesific attribute in form html. So your html will look like original and clean also you are more easier to separate your code between html and javascript.

  • Using ES5 standard (support IE9++)
    Many lightweight form validation out there is not using E5 standard. Most of them is jQuery plugins.

Please see this library at :

If you have any problem to use this library, just feel free to leave at this comment below.

Thank you for your time to reading my article.