validate-forms-with-validate.js

Introduction

In this tutorial, you will learn how to implement form validation using validate.js library.

You will learn how to add dependencies, build basic form structure and execute required functions to create fully
validated form with custom error messages and dynamically assigned errors depending on which type of error user
caused in your form.

Note: To understand this tutorial content you need to have some understanding about JavaScript and HTML’s form structure. I will do my best to explain everything in depth but you need to have some basic knowledge about this topic to use this useful extension.

,,Why should I waste my time for this?”

Validate.js is a lightweight library that depends on object constraints and function validate(). This simple structure gives us easy to understand logic about our rules of validation inside the object and receiving errors depending on our custom made rules with a designated function. After this tutorial, you will understand everything you need to build your first validated form with this technology.


See how easily you can modify your design of the form keeping the same validation methods.


Installation

To use validate.js you actually don’t need any external dependencies! However, you might want to add a way to
validate date and DateTime with custom parse and format function. For that purpose creator of
validate.js
recommend
using moment.js library.

Additionally, to show you we can use only clear javascript while using this library I will not use any jQuery
code
in this form aside initiation of our MDB components. To make this process easy I will use some basic functions
from underscore.js
to quickly operate on dom elements without building any external objects and functions.

My starting index.html file will look like this:

Note: You can use validate.js library without any other dependencies. I
will use external dependencies to show how you can implement complex form easily by using these additions.


Build an MDB Form

To check if the form is properly filled by users first we need to have a ready form.

In this tutorial I will try to showcase all the possibilities of this validating library, so we will need a variety of
input types.

This example showcase usage of basic input types like type="email", type="password",
type="text", type="date" or type="number" and additionally, some custom made
validation will check the validation of the select field.

To present how you can implement this validation in the real-life example I styled this form and prepared space in
bootstrap layout for errors display.

Note: Elements with class .messages will contain error
content.

The form that I will check with validate.js looks like this:


Let’s get started!

Step 1 – create constraints object

When working with validate.js this object is essential. Inside this structure, you define what attribute of input you
want to check, what input types you want to be checking, check your custom validator options and many more like
defining error messages.

We will use object constraints inside basic validate function of this library but let’s not overtake the topic.
First, we need our rules.

The basic structure of constraints object looks like this:

To create complex constraints object you have to consider all use cases of your form.

In my example form, we have all sort of different input types so we need to create constraints rules for all of
them.

Note: Element attribute is, in this example, the name tag inside our input
declaration. Validator name is one of the predefined names given by the library. Validator options are one of the given
values that given Validator name accepts.


Basic elements

Checking email

Validate.js is created by making our development easy in mind. Creators made commonly used features available to
use by default. For example to create constraints for basic email checking you have to create only these lines of
code:


Checking password

Checking if the password is enough long for our standards is simple and easy to:


Confirm password

This sometimes causes troubles during development but with validate.js you simply use default options given by the
library. We have the attribute equality which gives every possible feature you might need in checking equality of
your input fields.

To check if this element value is equal with another input type we need to create a structure like this:

In the HTML form I used the intuitive name for input that will require confirmation of the password but this name contained symbol ‘-‘. Because of that, we had to show the object that we still work with the name string. To accomplish that I simply wrapped the name of this validate attribute inside a string
apostrophe’s like this:

"confirm-password":

In this example, we created a custom message for our new constraints rule which is ‘equality’. For email and password validation we have predefined messages that we can use if we want to but for our custom rules, we have to create our messages that we want to display in case of an error.

Note: Creating custom messages might be useful to create different language versions for your form validation.


Check the input content – Username

In our services we want our users to have standardized usernames. We can create this sort of in-depth checking with validate.js. In my example, I will require username to exist, have a length between 3 and 20 string length, contain only letters and digits but we don’t want to check if letters are upper or lower case.

With standard validation options, we most likely would create a complex function that would check all these elements by parsing our input value. With validate.js you can accomplish that by simple object structure:

In the example above I tried to explain every element used by adding comments. Because of this object great structure, every part of the required code is easy to understand and after the first implementation, everything seems to be intuitive.

Note: To find out every possible predefined attribute you can check their list in full documentation on the creator’s site.


Age restriction – Date

This kind of verification can be achieved by a countless amount of ways. In this example, I will use the library that I mentioned at the beginning moment.js. This addon makes my birthdate verification 4 lines long:

Like always we check if the element exists with presence: true,. This time we need to use default date attribute and check it with the latest value to ensure the data we get in the date input is not later than the declared value.

This may be not intuitive but using the function moment().subtract(18, "years") I check what moment it is right now and what is the year someone had to be born to be at least 18 years old.

Because I declared new validation rule I declared additional error message if this rule is not fulfilled.

This is that simple!


Checking select field – Country

This part will demonstrate how to implement validation with our mdb material select. This component causes many troubles in the past with validation implementation but with validate.js it is much easier.

In the form I created to demonstrate this type of validation you can see that the list of options is quite large but every single one has an attribute: value="" with country code in it. Because of this addition, we can check what option is picked more intuitive.

In this example, we used two new attributes: inclusion and within.

Inclusion checks if the input value is the same as any element from the “within” table. In this example, I declared only a select option with attribute value="SE" which is Sweden.

Note: Inclusion gives you the opportunity to check if the input value matches one of many options you declare as valid. Simply extend it within the table with more strings separated by a comma.

We almost finished, let’s understand the last two types of constraints declared in my example.


Checking optional field – Zip Code

In declaring constraints I used presence: true in all examples above but this element is not required to exist in every single validated attribute. This time I present you simple constraints example of how you can check if the validated input fits your rules.

This time my declaration want this input to contain 5 digits. I achieve this validation this way:

As you may notice in format attribute we use pattern with value wrote using regExp to declare what type of string we accept.

Note: To read more about this element visit this documentation site

This input will not be validated unless someone types something in it. If at the moment of checking the form value will be empty there will be no verification of this input but if the content of the input exists and doesn’t match our pattern rules the user will receive an error message.


Checking number field

The last element we want to validate is number input with restriction to accept only an integer value equal to or greater than zero.

Achieving this with validate.js is simple:

Code in this example basically explains itself. After watching previous examples this one is trivial, isn’t it?

To check numerical values we use to attribute numericality with some basic expressions like “only integer” and “greaterThanOrEqualTo”.

Note: To read more about numerical validation rules check this documentation site

And… We did it! Our Constraints are ready to be validated.


Validation in action

Like in every form we need to add some basic js functions before we start creating our features. In this example, I create an extended validation rule for date checking to accept the desired format.

After all my rules are ready to be used I hooked up the form to prevent it from being posted and instead execute a custom function.

After the form submits event my handleFormSubmit() function will be executed. Let’s create this function now!

This simple function checks if validating function after checking our form returns any errors according to our predefined constraints. We execute function showErrors() if any error exists or showSuccess() if there are none.

Let’s create both functions:

Inside our loop, we execute the function for every single input to show it’s errors and as explained in comments, we have to handle errors that contain null. To achieve that we create the function showErrorsForInput() that will do exactly that.

This function will be more complex so let’s read this carefully with my comments:

In the function above we use functions closestParent, resetFormGroup, addError and element item but we didn’t declare them before. Let’s fix it now!

First, we create the input variable:

In this code, I created not only an input element but additionally a loop that will iterate through all inputs that we find and proceed with some intentional methods.

We want to know if any input was changed and if that is a truth we execute code inside this event function. Generate new errors depending on this state of form and execute a function that will show this direct input new error.


Now I will declare a function closestParent(). We will use this function to find a place for our error messages. My structure of HTML assumes that my errors will be displayed inside of a grid structure so I just need to reach a div that is a sibling to our inputs div with class .md-form.

This function will look like this:

We just check if the attribute child received an element that can actually be a nested element and if that is true, checks if this element contains the class that we want to actually find. If not we reach .parentNode element and execute the function once more. So the only expected outputs are null if we reach document without finding the desired class or actually an element that we are looking for.

Our form validation is almost ready. The only missing parts are functions resetFormGroup and addError.

To achieve reset of a form group we just clear previously added classes and remove elements containing errors.

So, for now, we check our form and take care of all the possible outcomes but we didn’t add the main part of this whole event. How actually we add our errors to the form?

Check out this function:

And that’s it. We just have to assemble all the pieces and execute them in (function() { })( ); object.

I added one mdb element to the mix so we have to initialize MDB material select with this code:

It is done!

We created a fully functional front end form with various validation methods and our custom set of rules. Our final result should contain this code:

Conclusion

Validate.js is helpful library to create all sort of validation rules and complex solutions. You can customize every single point of your form without hesitation. If you don’t want to build jQ dependant form validation with our MDB Package I highly recommend using this library to build your own form constraints.


Note: Don’t forget to show us your form with custom validation in our snippets

57 comments

  1. Ahaa, its pleasant dialogue on the topic of this paragraph here
    at this webpage, I have read all that, so now me also commenting at this place.

  2. Saya telah berselancar online lebih dari tiga jam hari
    ini, namun saya tidak pernah menemukan artikel menarik seperti milik Anda.
    It’s cukup berharga bagi saya. Secara pribadi ,
    jika semua pemilik web dan blogger membuat konten yang baik seperti yang Anda lakukan, web akan menjadi lebih berguna dari sebelumnya.

    Here is my blog Joker123 download apk

  3. Way cool! Some extremely valid points! I appreciate you penning this write-up
    and the rest of the website is very good.

  4. Saya akan segera genggam rss feed Anda karena saya
    tidak bisa
    Sangat keren! Beberapa poin yang
    Saya sangat suka apa yang kalian ada juga. Seperti pekerjaan cerdas dan keterpaparan !

    Pertahankan bagus karya kawan-kawan yang telah saya tergabung kalian ke

    Sungguh menyukai situs web Anda .. Warna & tema Luar biasa .
    Apakah Anda sendiri yang membuat situs web ini ? Harap balas kembali karena saya berencana untuk membuat milik saya situs web dan akan senang untuk mencari tahu dari mana Anda mendapatkan ini
    atau persis apa tema dinamai. Terima kasih !

    Also visit my site :: Slot joker mod apk

  5. Saya telah berselancar online lebih dari 4 jam hari ini, namun saya tidak pernah
    menemukan artikel menarik seperti milik Anda.
    It is cukup berharga bagi saya. Dalam pandangan saya, jika semua pemilik situs web dan blogger membuat konten yang baik seperti yang Anda lakukan, net akan menjadi a jauh
    lebih berguna dari sebelumnya.

    Also visit my blog joker123 slot (https://gameaco.com/empat-contoh-joker123-exe-yang-Memukau/)

  6. Just want to ssaʏ your article is as amazing.
    The clearness in your post is simply сool and i could assume you are an expert on thus subject.

    Fine witһ your ⲣermission let me to grab ykur RSS
    feed to keep updated with forthcoming post. Thanks a million and please carr on the rewarɗing wߋrk.

  7. Please let me know if you’re looking for a article author for your site.

    You have some really great articles and I feel I would be
    a good asset. If you ever want to take some of the load off, I’d love to write some material for
    your blog in exchange for a link back to mine. Please send
    me an email if interested. Thanks!

    my blog: game mega888 (Bert)

  8. An outstanding share! I’ve just forwarded this onto a coworker who
    was conducting a little homework on this. And he in fact
    ordered me dinner because I discovered it for him…
    lol. So let me reword this…. Thank YOU for the meal!!
    But yeah, thanx for spending some time to discuss this topic here on your site.

    Take a look at my website … download game mega888

  9. What i don’t realize is in truth how you’re not really much more smartly-liked than you might be now.
    You are so intelligent. You understand thus considerably in the case
    of this subject, produced me for my part imagine it from a lot of various angles.
    Its like women and men don’t seem to be fascinated unless it’s
    one thing to accomplish with Woman gaga! Your personal stuffs great.
    Always take care of it up!

    my blog: Xe88 malaysia (http://yui.saikyoh.jp)

  10. I’m more than happy to find this site. I want to to thank you for ones time due
    to this wonderful read!! I definitely loved every bit of it and i also have you
    book-marked to check out new information on your website.

    Review my website :: download mega888 (cmello.com.br)

  11. Thank you for the auspicious writeup. It in fact was
    a amusement account it. Look advanced to far added agreeable from you!
    However, how could we communicate?

    my web site … gamexe88

  12. I do agree with all the concepts you’ve introduced in your post.
    They are very convincing and can definitely work.
    Nonetheless, the posts are too brief for beginners. May just you please lengthen them a little from subsequent time?

    Thanks for the post.

    My web site kiss918 xe88

  13. Saya telah berselancar online lebih dari tiga
    jam hari ini, namun saya tidak pernah menemukan artikel menarik
    seperti milik Anda. It’s cukup berharga bagi saya.

    Menurut pendapat saya , jika semua webmaster dan blogger membuat konten yang baik
    seperti yang Anda lakukan, web akan menjadi
    lebih berguna dari sebelumnya.

    my webpage :: Roma joker123

  14. Hi there, just became aware of your blog through Google, and found
    that it is really informative. I’m going to watch out for brussels.

    I will be grateful if you continue this in future.
    Numerous people will be benefited from your writing. Cheers!

    My website :: xe888

  15. I feel this is among the such a lot significant information for me.
    And i’m glad reading your article. However wanna commentary on some general issues, The
    site taste is perfect, the articles is actually nice :
    D. Good task, cheers

    Here is my web site … mega888 ios

  16. Its like you read my mind! You appear to know so
    much about this, like you wrote the book in it
    or something. I think that you can do with a
    few pics to drive the message home a bit, but other
    than that, this is magnificent blog. An excellent read.
    I will definitely be back.

    Visit my web blog: mega888 singapore

  17. Very nice post. I just stumbled upon your weblog and wanted to say that I have
    truly enjoyed surfing around your blog posts. After all I’ll be subscribing to your feed and I hope you write again soon!

    Feel free to surf to my site … 918Kaya hack Apk

  18. It’s a shame you don’t have a donate button! I’d most certainly donate to
    this outstanding blog! I guess for now i’ll settle for book-marking and adding your RSS feed to my Google account.
    I look forward to new updates and will share this blog with my Facebook group.
    Talk soon!

    Review my homepage :: mega888 original (wiki.ej-ffb.de)

  19. Hello, I think your website might be having browser compatibility
    issues. When I look at your blog site in Firefox, it looks fine but when opening in Internet Explorer,
    it has some overlapping. I just wanted to give you a quick heads
    up! Other then that, awesome blog!

    Also visit my homepage: pussy888

  20. I’ve been browsing on-line greater than three hours as of late,
    yet I never discovered any attention-grabbing article like yours.
    It is pretty value enough for me. Personally, if all web owners and bloggers made just right content
    as you did, the internet might be a lot more helpful than ever before.

    my site :: 918kiss trusted company

  21. Hello! I’m at work surfing around your blog from
    my new apple iphone! Just wanted to say I love reading your blog and
    look forward to all your posts! Keep up the outstanding work!

    Take a look at my web site … Game Xe888

  22. Hey I know this is off topic but I was wondering if you knew of any widgets I could add to my blog that automatically tweet my newest twitter updates.
    I’ve been looking for a plug-in like this for quite some time and was hoping maybe you would have some experience with something like this.
    Please let me know if you run into anything. I truly enjoy reading your blog and I look forward
    to your new updates.

    My site … 918Kiss Pc

  23. For hottest information you have to visit world-wide-web and on internet I found this web site as
    a finest website for newest updates.

    Here is my web page: kiss916

Leave a Reply

Your email address will not be published.