Javascript, Jquery form validation using Functional Programming techniques

I just put this together for a little project at work today and thought I'd share it with the world. 

By using Functional Javascript techniques, this bit of Javascript code is extremely easy to drop into any web form to validate the input fields. It uses two functional programming techniques: map and reduce. Together with jQuery (a library heavily reliant on Javascript's functional capabilities), this validation function is extremely flexible and extendable. For example, if you dont' want all input fields to be required, then you can create an html class "required" or "not_required" or something and modify the jquery selector on line 7 for this. Or if you need to control which form(s) on the page gets validated, you can update the jquery selector on line 2. To learn more about functional programming in Javascript, please consider purchasing my new book Functional Programming in JavaScript. Thanks!

Here's the JSFiddle:

  1. //  Bind the event handler to the "submit" JavaScript event
  2. $('form').submit(function () {
  3.     // return true only if all inputs have text in them, false if otherwise
  4.     return
  5.         // first argument is the 'this value', we need an array
  6.         // map over the array of inputs, check if empty or not, returns array of trues and falses
  7.         $('input, textarea').map(function(i, x){
  8.             // Check if empty of not
  9.             var text = $.trim($(x).val());
  10.             if (text  == '') {
  11.                 alert($(x).attr('name') + ' is empty. All inputs are required.');
  12.                 return false;
  13.             } else {
  14.                 return true;
  15.             }
  16.         }),
  17.         // the reduce function, true && false == false
  18.         function(a,b){
  19.             return a && b
  20.         },
  21.         // initial value
  22.         true);
  23. });