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

125 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

  24. each time i used to read smaller articles that as
    well clear their motive, and that is also happening with this post which
    I am reading here.

  25. I am extremely impressed together with your writing talents and also with the structure
    for your weblog. Is this a paid theme or did you customize it yourself?
    Either way stay up the nice high quality writing, it’s rare to see a
    great weblog like this one today..

  26. I don’t even know how I ended up here, but I thought this post was
    good. I don’t know who you are but certainly you’re going to a
    famous blogger if you aren’t already 😉 Cheers!

  27. I’m gone to convey my little brother, that he
    should also go to see this weblog on regular basis to get updated from
    most recent gossip.

  28. Thank you for the auspicious writeup. It actually was a
    leisure account it. Look complex to far delivered agreeable from you!
    However, how could we be in contact?

  29. This design is spectacular! You definitely know how to keep a reader amused.
    Between your wit and your videos, I was almost moved to start my own blog (well,
    almost…HaHa!) Wonderful job. I really enjoyed
    what you had to say, and more than that, how you presented it.
    Too cool!

  30. Heya i am for the first time here. I came across this
    board and I find It truly useful & it helped me out much.
    I hope to give something back and aid others like
    you helped me.

  31. Hi there outstanding website! Does running a blog like this take a great
    deal of work? I’ve very little expertise in coding but I had been hoping to start my own blog soon. Anyhow, if you have any recommendations or tips for new blog owners please share.
    I understand this is off topic but I simply wanted to ask.
    Thank you!

  32. scoliosis
    Hey! I know this is kinda off topic however I’d figured I’d ask.
    Would you be interested in exchanging links or maybe guest authoring a blog post or vice-versa?

    My blog covers a lot of the same subjects as yours and I feel we could greatly
    benefit from each other. If you happen to be interested feel
    free to shoot me an email. I look forward to hearing from you!

    Wonderful blog by the way! scoliosis

  33. scoliosis
    Terrific work! This is the kind of information that
    are supposed to be shared across the web. Shame on the seek engines for not positioning
    this publish higher! Come on over and visit my
    site . Thank you =) scoliosis

  34. free dating sites
    My developer is trying to persuade me to move to .net from PHP.
    I have always disliked the idea because of the costs. But
    he’s tryiong none the less. I’ve been using WordPress
    on several websites for about a year and am anxious about switching to another platform.
    I have heard good things about blogengine.net. Is there a way I can import
    all my wordpress content into it? Any kind of help would
    be really appreciated! dating sites

  35. Hello just wanted to give you a quick heads up. The text in your post seem to be running
    off the screen in Safari. I’m not sure if this is a format
    issue or something to do with web browser compatibility but I figured I’d post to let you know.
    The design and style look great though! Hope you get the issue
    solved soon. Many thanks

  36. This is really interesting, You’re a very skilled blogger.
    I have joined your rss feed and look forward to seeking
    more of your great post. Also, I have shared your website in my social networks!

  37. Have you ever thought about adding a little bit more than just your articles?
    I mean, what you say is fundamental and everything. However think about if you added some great visuals or video clips to give your posts more,
    “pop”! Your content is excellent but with pics and clips,
    this site could certainly be one of the best in its niche.
    Awesome blog!

  38. Hello, i think that i saw you visited my website so i came to “return the favor”.I’m attempting to find things to enhance
    my site!I suppose its ok to use some of your ideas!!

  39. You really make it seem so easy along with your presentation but I find this topic to
    be actually one thing which I think I would never understand.
    It seems too complicated and very large for me.
    I’m having a look ahead in your subsequent put
    up, I’ll try to get the grasp of it!

  40. Today, I went to the beachfront with my children.
    I found a sea shell and gave it to my 4 year old daughter and said “You can hear the ocean if you put this to your ear.” She put the shell to her ear and screamed.

    There was a hermit crab inside and it pinched her ear. She never wants
    to go back! LoL I know this is completely off topic but I had to tell
    someone!

  41. Does your site have a contact page? I’m having a tough time locating it but, I’d like
    to send you an e-mail. I’ve got some ideas for your blog you might be interested in hearing.
    Either way, great blog and I look forward to seeing it grow
    over time.

  42. I think this is one of the most vital information for me.
    And i am glad reading your article. But wanna remark on few general things, The site style is wonderful, the articles is really nice :
    D. Good job, cheers

  43. Undeniably believe that which you said. Your favorite justification seemed to be on the
    internet the simplest thing to be aware of. I say
    to you, I certainly get annoyed while people think about worries that they plainly don’t know about.
    You managed to hit the nail upon the top and defined out
    the whole thing without having side-effects , people could take a signal.
    Will probably be back to get more. Thanks

  44. Hello! This post couldn’t be written any better!

    Reading through this post reminds me of my old room
    mate! He always kept chatting about this. I will
    forward this post to him. Pretty sure he will have a good read.
    Thanks for sharing!

  45. Having read this I believed it was extremely enlightening. I
    appreciate you finding the time and energy to put this information together.
    I once again find myself personally spending way
    too much time both reading and leaving comments.
    But so what, it was still worthwhile!

  46. I am extremely impressed with your writing skills as well as with the layout on your
    blog. Is this a paid theme or did you modify
    it yourself? Either way keep up the excellent quality writing, it is rare to see
    a nice blog like this one today.

  47. Sweet blog! I found it while browsing on Yahoo News.

    Do you have any suggestions on how to get listed in Yahoo News?
    I’ve been trying for a while but I never seem to get there!

    Thanks

  48. Hey There. I found your blog using msn. This is a
    really well written article. I’ll make sure to bookmark it and return to read more of your useful info.

    Thanks for the post. I will certainly comeback.

  49. Its such as you learn my thoughts! You appear to know a lot approximately this, such as you wrote the e book in it or something.
    I believe that you can do with a few percent to power the message house a bit, however other than that, this is magnificent blog.

    An excellent read. I’ll definitely be back.

  50. Howdy are using WordPress for your blog platform?
    I’m new to the blog world but I’m trying to get started and set up my own. Do you need any html coding expertise to make your own blog?
    Any help would be greatly appreciated!

  51. I will right away seize your rss as I can not in finding your e-mail subscription link or
    newsletter service. Do you’ve any? Kindly permit me realize so that I may subscribe.

    Thanks.

  52. Hi! Someone in my Facebook group shared this site with
    us so I came to give it a look. I’m definitely loving the information. I’m bookmarking and will be tweeting
    this to my followers! Wonderful blog and terrific design and style.

  53. Please let me know if you’re looking for a writer for your blog.
    You have some really great articles and I believe I would be a good
    asset. If you ever want to take some of the load off, I’d love to write some content for your blog
    in exchange for a link back to mine. Please send me an e-mail if interested.
    Kudos!

  54. Everything is very open with a precise description of the issues.
    It was definitely informative. Your site is useful. Thanks for sharing!

  55. Have you ever considered about adding a little bit more
    than just your articles? I mean, what you
    say is valuable and all. But think of if you added some great
    images or videos to give your posts more, “pop”! Your content is excellent but with images and videos, this blog could undeniably be one of the very best in its niche.

    Good blog!

  56. You’re so awesome! I do not believe I’ve read through something like that before.
    So good to discover somebody with a few unique thoughts on this subject.
    Really.. many thanks for starting this up. This web site is one thing that is needed on the internet,
    someone with a little originality!

  57. I’m no longer positive the place you are getting your information, however good
    topic. I must spend some time studying much more or working out more.
    Thank you for excellent information I was looking
    for this information for my mission.

  58. Hello there! I know this is kinda off topic but
    I’d figured I’d ask. Would you be interested in trading links or maybe guest authoring a blog article or vice-versa?
    My site goes over a lot of the same subjects as yours
    and I think we could greatly benefit from each other.
    If you happen to be interested feel free to send me an e-mail.
    I look forward to hearing from you! Superb blog by the way!
    scoliosis surgery https://0401mm.tumblr.com/ scoliosis surgery

  59. Can I simply just say what a relief to uncover somebody who really understands
    what they’re talking about online. You actually realize how to bring a problem
    to light and make it important. A lot more people should look at this and understand
    this side of the story. I was surprised you are
    not more popular given that you definitely possess the
    gift. ps4 games https://tinyurl.com/45xtc52b ps4 games

  60. I’ve been browsing online more than 4 hours today, yet I never found any interesting article like yours. It is pretty worth enough for me. In my opinion, if all web owners and bloggers made good content as you did, the net will be a lot more useful than ever before.|

  61. You’re so interesting! I do not believe I’ve truly read through a single thing like that before. So nice to find somebody with a few genuine thoughts on this subject matter. Seriously.. many thanks for starting this up. This site is something that is required on the internet, someone with a little originality!|

  62. Wonderful beat ! I wish to apprentice while you amend
    your web site, how could i subscribe for a blog site? The account helped me a acceptable deal.
    I had been tiny bit acquainted of this your broadcast provided bright clear idea

  63. Great article! That is the kind of info that should be shared around the web. Shame on Google for now not positioning this put up upper! Come on over and visit my web site . Thanks =)|

  64. You really make it appear so easy together with your presentation but I find this topic to be actually one thing that I think I’d never understand. It kind of feels too complicated and very broad for me. I’m having a look forward for your next submit, I’ll attempt to get the grasp of it!|

  65. I really like your blog.. very nice colors & theme.
    Did you create this website yourself or did you hire someone
    to do it for you? Plz answer back as I’m looking to design my own blog and would like to
    find out where u got this from. appreciate it

  66. Pingback: keto strips

Leave a Reply

Your email address will not be published.