Skip to content

Instantly share code, notes, and snippets.

@maclennann
Last active August 29, 2015 14:09
Show Gist options
  • Save maclennann/5a6cb955eec6df664229 to your computer and use it in GitHub Desktop.
Save maclennann/5a6cb955eec6df664229 to your computer and use it in GitHub Desktop.
jquery simpleValidator plugin

This is probably fairly straightforward, but I find myself constantly making boilerplate plugins like this. simple-validator is a small, opinionated validator that is useful for checking text in textboxes against external APIs.

This is helpful in the following flow:

  • Given: an input textbox that may be validated (not required)
  • Given: a "validate" button that may or may not be clicked before the user submits the form
  • Given: a "validation message" span
  • When: The user clicks the "validate" button.
  • Then: The text in the input textbox is submitted to an external API via AJAX
  • And: The results are printed to the "validation message" span

If you need something bigger, better, and more powerful, look toward jquery-validation or any of the myriad other validation plugins.

Dependencies

  • JQuery (probably any version. this was written against 2.0.3 fwiw)

Optional

  • font-awesome (4.1.0 and 4.2.0 have been tested, but it just uses that cute little spinning circle)

How To Use

Basically, you bind it to your button, tell it how to find your input and output elements, and tell it what it's supposed to use for a validator.

$("#button").simpleValidator("#textbox", "#messagespan", validationFunction);

Demo

There is a demo file in this gist. You can see it live here.

Advanced Usage

This is getting a little bit into "use a real plugin" territory, but javascript's golden rule is "you can make anything do anything if you try hard enough."

So maybe you want your button to validate an entire form instead of just a single input textbox? Sure.

    // A small abuse of simpleValidator by not providing an inputSelector and making our in-line
    // validation function read the entire form.
    $('#formsubmit').simpleValidator(null, "#validation", function() {
        event.preventDefault();
        var item1 = $("#item1").val();
        var item2 = $("#item2").val();
        var item3 = $("#item3").val();
        var item4 = $("#item4").val();
        var item5 = $("#item5").val();

        var url = '/validate/my/form';

        return an.ajax.call.wrapper(url, item1, item2, item3, item4, item5);
    });
<html>
<head>
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet">
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
<link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<!--This is a live version of the javascript from the repo.-->
<script src="http://rawgit.com/maclennann/5a6cb955eec6df664229/raw/d304d6e3b8f8498f651230276d8200a113376e3e/jquery-simplevalidator.js"></script>
</head>
<body style="margin-left:20px">
<h3>Demo 1</h3>
<p>This just takes the text of your textbox, waits 2 seconds, and spits it back with fixed message prepended.</p>
<input id="input" type="text" value="lawlwut" />
<button id="action" type="submit">do it? </button>
<br/>
<span id="output"></span>
<script type="text/javascript">
$(function() {
// This could just as easily have been in-lined in this case, but
// I left it separate since that's how you should probably use it.
// This just returns a promise, then waits two seconds to return
// some text.
var fakeValidator = function(text) {
var deferred = new $.Deferred();
setTimeout(function() {
deferred.resolve("two seconds ago, you told me: " + text);
}, 2000);
return deferred.promise();
};
// Here's where the magic is happening!
$("#action").simpleValidator("#input", "#output", fakeValidator);
});
</script>
<br/><br/><br/>
<h3>Demo 2</h3>
<p>This one makes an AJAX request with your message to cors-test.appspot.com/test.<br/>
using the built-in urlValidator. The outupt doesn't vary.</p>
<input id="input2" type="text" value="nothing"/>
<button id="action2" type="submit">again?</button>
<br/>
<span id="output2"></span>
<script type="text/javascript">
$(function(){
// More magic!
$("#action2").simpleValidator("#input2", "#output2", $.simpleValidator.validators.urlValidator("https://cors-test.appspot.com/test","GET","something"));
});
</script>
</body>
</html>
// A simple JQuery plugin that runs the value in a text box against a validation
// action and prints the results to a div.
//
// Binds to a button and runs on-click.
//
// dataSelector must be a selector that targets a textbox (your input for validation)
// resultSelector must be a selector that targets a div into which the validation results are printed
// validationAction must be a function that expects a string and returns a promise
$.fn.simpleValidator = function(dataSelector, resultSelector, validationAction) {
// Store all this so the closure has access when we actually have to run it.
var button = this;
var results = $(resultSelector);
var action = validationAction;
var textBox = $(dataSelector);
var validate = function() {
var dataValidator = new $.simpleValidator.ui.spinningButton(button);
dataValidator.spinButton();
action(textBox.val()).done(function(result) {
results.html(result);
})
.fail(function(data, statusText, error) {
results.html("Error! " + status + "<br/>" + error);
})
.always(function() {
dataValidator.stopButton();
});
};
button.on('click', function(event) {
event.preventDefault();
validate();
});
}
$.simpleValidator = $.simpleValidator || {};
$.simpleValidator.ui = $.simpleValidator.ui || {
spinningButton: function(selector) {
var button = $(selector);
var spin = function() {
if (button.children(".fa").length !== 1) {
button.append("<i class='fa'></i>");
}
$(button).children(".fa").addClass("fa-circle-o-notch fa-spin");
},
stop = function() {
$(button).children(".fa").removeClass("fa-circle-o-notch fa-spin");
};
return {
spinButton: spin,
stopButton: stop
};
}
};
$.simpleValidator.validators = $.simpleValidator.validators || {
// Built-in validator to post the contents of your textbox to a url
// Whatever the server sends back will be dropped into the result element
urlValidator: function (url, method, paramName) {
return function (paramValue) {
var data = {};
data[paramName] = paramValue;
return $.ajax({
url: url,
contentType: 'application/json',
dataType: 'html',
type: method,
data: data
});
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment