logo

Simple OO JavaScript Form Validation

Turns out Object Orientated JavaScript is a doddle. So easy even I can do it! In fact I've been doing it for a while now, without even realising it.

Let's look at an example of creating a simple form validation object. To create the Object it's as easy as this:

var Validator = {
}

This would be done in an external .js code library and the Validator object would then be available throughout our code.

To extend the Object we can add "properties" and "methods" to it. Here's how to add a couple of properties:

var Validator = {
 version: '1.0.0',
 form: document.forms[0]
}

Now we can refer to this in our code. For example, alert(Validator.version) would give us 1.0.0. Or we could have alert(Validator.form.FieldName.value).

Note that we've hard coded the form in the Validator Object, which is never a good idea. Better to set this from the page itself, as we never know how many forms there might be. To do this we can add an "init" method to the Validator, like so:

var Validator = {
 version: '1.0.0',
 init: function(frm){ this.form = document.forms[frm] }
}

When our page loads we can now setup the validator like so:

<body onload="Validator.init('_Form_Name')">

All very well, but what about validation? Well, let's add another method that does some very basic validation, like so:

var Validator = {
 version: '1.0.0',
        
 init: function(frm){this.form=document.forms[frm]},
        
 validate: function(fld){
  if (this.form[fld].value==""){
    alert("Validation failed\n\nValidator v"+this.version);
    return false;
  } else { 
    return true;
  }
}

Now we have a method called validate() to which we can pass a field name. If that field is blank an alert is shown and the return value is false, which can be used to prevent a form being submitted, as below:

<form onsubmit="return Validator.validate('FirstName')">

Here's an example of this code in use. Alone it's a fairly useless example — a form that validates one field. What it should do is show how easy is to code OO-style in JavaScript.

Are there benefits to coding like this? I'm not sure. It makes me feel like a real programmer though and that's as good a reason as any ;o)

Nice article on Object-Oriented Javascript

Comments

  1. Of course there are benefits. I mentioned adding a widget more than once to a form a couple of days ago. So to extend the example, you could create a couple of objects, say FormValidator and ValidatorRule. Your FormValidatorInit could receive a string array of fieldnames, and maybe RegEx pattern pairs, with which it would create a chiled collection or array of ValidatorRule objects. FormValidator.isValid would be called from your onsubmit and would simply need to query each Validator.Rule.isValid method to see if FormValidator.isValid returns true or false.

    That's the rough workflow. The object topography would of course be a bit more detailed, but you get the idea. Now I can init FormValidator with multiple fields (or other things), each of which simply becomes a ValidatorRule, which can contain all the methods I need for each items validation logic based on how it was initialized by FormValidator.

    Very useful when I don't have to unravel miles of conditional logic, or rewrite said lagic, everytime I add a field.

  2. OO Javascript is really easy once you get the hang of it, once you get the basics down I really reccomend taking a look over at prototype and all the functionality it can add to OO javascript. I saw you post about a validation routine based on prototype the other day, which is very similar to mine, though I prefer my coding style (who doesn't prefer their own :). Here's the first article I wrote about the validation {Link} and here's the SnTT I wrote on how to add it into a domino form {Link}

    I tried to keep it very simple to expand on so that custom validation routines would be simple to add. Hope someone finds it helpful.

    • avatar
    • GM
    • Fri 26 May 2006 08:12 AM

    For form validation I don't see the need for something like a "Validator" object - it seems to be a waste of time and energy to go through so much trouble to validate a form on the client side, when the user can freely circumnavigate this code. On the server-side, however, I can understand it fully, although there you wouldn't be using Javascript, obviously. On the client side, a basic "Is the field empty?", "Is the field a number?", "Is the value within this range?" type of validation is usually sufficient.

    I think Javascript objects are much more useful and relevent in creating DHTML elements - I use JS objects for sortable tables, collapsable sections, appearing/disappearing areas etc. and there I find JS objects almost indispensable.

    • avatar
    • MoGryph
    • Fri 26 May 2006 02:23 PM

    GM- I tend to disagree- the less traffic you have going back and forth to/from a server, the better. I don't see any reason for not validating again on the server side (in case you believe that you've got those sneaky users circumventing the system), but if you can reduce the extra baggage for the simple users, all the better. Back/forth communication doesn't just reduce server response time, but can really irritate end-users if things are slow. Most end-users would prefer to have an immidiate message telling them they've missed something, rather than- Submit.... wait... dang, I messed up- fix it, submit... wait.... Ah... finally. If they never have to say "Ah... finally" because of multiple slow submits, then we've done our job correctly.

    I've used OO JS Objects for validation before, only in a different manner.

    I've got a few databases out there, where the best way I was able to build them, meant that they needed Computed subforms. Yeah, yeah, I know they're supposed to slow stuff down, but it was the only way I could think of doing some of the things I was trying to accomplish.

    The headache showed up, when I was trying to figure out the best way to validate fields, regardless of which subform(s) were added to the form, without building one huge bloated JS file that 90% of which might never have been used by most of the users.

    What I ended up doing, was creating a global JS Validator object that contained an empty collection variable, and a function to add new Validation functions to the collection.

    At the top of each of the subforms that might be added, I had a custom validation function, and used Validator.addValidation(thisFunction). Thinking back, it probably would have been better to have each of the functions imported from their own separate .js files. Ah... Hindsight.

    Then, in my OnSubmit, I just called Validator.validate(), which enumerated all the functions in the container object, collected comments for each validation that failed (they returned a message on failure, and "" on success) and alerted a single message for all errors. It kept things nice and nice and clean and dynamic.

    • avatar
    • MoGryph
    • Fri 26 May 2006 02:56 PM

    Oh yeah, and here are a couple of great links for learning some more fine and amazing nitty-gritty points of JavaScript OO.

    Inheritance: link

    Private/Priveleged methods:

    Link

    The guy's got a page with a bunch of links for Javascript, here:

    {Link}

    Lots of advanced stuff.

  3. I agree with MoGryph. OO Js not only isn't that hard, as Jake has found, once you get into it, and reusable (code once use often), Client side JS is a courtesy to the user. Would you rather wait for a form to submit and then get a page returned to you with modifications or some other alert telling you where the error are (most shopping forms online come to mind) or would you rather know about input miistakes as each field is completed?

    There are some great arguments for making the UI nicer, especially where not frustrating the user could be the difference between a new customer and lost business.

    I do agree with GM though that you do need server side validation for the stated reason that you can get 'round JS validation if you want to.

    I think this conversation has happened already in the past here on Codestore... the gist being do both. Client for the customer, server for the data.

  4. man thanks for writing this... you do make it seem simple!

    • avatar
    • Paul
    • Fri 17 Oct 2008 09:07 AM

    Great article! I'll just have to say that if you are writing to a database, both server and client-side validation are essential. Server side is not necessarily for the user's benefit, but for the "cleanliness" of the data. I am not interested in providing a nice response to users who choose to circumvent client side validation so checking on the server is for me, strictly to prevent anything malicious from being written to the database.

Your Comments

Name:
E-mail:
(optional)
Website:
(optional)
Comment:


About This Page

Written by Jake Howlett on Thu 25 May 2006

Share This Page

# ( ) '

Comments

The most recent comments added:

Skip to the comments or add your own.

You can subscribe to an individual RSS feed of comments on this entry.

Let's Get Social


About This Website

CodeStore is all about web development. Concentrating on Lotus Domino, ASP.NET, Flex, SharePoint and all things internet.

Your host is Jake Howlett who runs his own web development company called Rockall Design and is always on the lookout for new and interesting work to do.

You can find me on Twitter and on Linked In.

Read more about this site »

More Content