jQuery Validations In A Script File

back to tech articles
jQuery 1.10.2

This is pretty straightforward really. I want to keep all my validations in a seperate file and call them to act on a specific form after the page has fully loaded. I keep forgetting the syntax, so this is as much for me in future as for you!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
(function($){
    var validateInputForm = function(domSelector) {
        $('#' + domSelector).submit(function() {
            var fileInput = $(':file', '#' + domSelector);
            if (fileInput.val() == '') {
                alert('Please select a file for: ' + fileInput.attr('name'));
                return false;
            }
        });
    }
    $(document).ready(function() {});
    $(window).load(function() {
        validateInputForm('my_form_id');
    });
})(jQuery);

This belongs in an external file.

Then, the file is included in the page within script tags, after the jQuery library has been included. That’s it really. We call the function and set the DOM selector on window load in this case, but it could also be set on the document ready event, it’s up to you.

For completeness, here’s the HTML as well:

1
2
3
4
5
6
7
<form id="my_form_id" enctype='multipart/form-data' action='' method='post'>
    <label for="my_file">
        <span>Select A File: </span>
        <input id="my_file" type="file" name="my_file" />
    </label>
    <button type="submit">upload</button>
</form>

Hope it helps!