Javascript, Jquery form validation using Functional Programming techniques

Submitted by Dan on Tue, 10/20/2015 - 15:50

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: http://jsfiddle.net/987gm8wy/

// Bind the event handler to the "submit" JavaScript event
$('form').submit(function () {
// return true only if all inputs have text in them, false if otherwise
return Array.prototype.reduce.call(
// first argument is the 'this value', we need an array
// map over the array of inputs, check if empty or not, returns array of trues and falses
$('input, textarea').map(function(i, x){
// Check if empty of not
var text = $.trim($(x).val());
if (text == '') {
alert($(x).attr('name') + ' is empty. All inputs are required.');
return false;
} else {
return true;
}
}),
// the reduce function, true && false == false
function(a,b){
return a && b
},
// initial value
true);
});