Taking a shot at creating a Meteor package, how does this look?


#1

I haven’t been able to find any good guides on how to make your own Meteor packages, so I just kind of blindly took a shot at this. It’s nothing special, just a simple form validator that checks for blank fields. Code is below.

One thing I’m not clear about is how to namespace this thing. How do I name the function so that it doesn’t potentially conflict with something else (FormValidator is a fairly generic name). Of course, if I’ve done anything else wrong here, feel free to chime in.

csjFormValidator = function(form, options) {
  // Override any default values. Defaults work well with Bootstrap 3
  var o = $.extend({}, {
    errorClass: 'has-error',
    reqFieldSelector: '[data-required]',
    addErrClassTo: '.form-group'
  }, options);

  $(form).find(o.reqFieldSelector).each(function() {
    if ($(this).val() === '') {
      $inputField = $(this);
      $errField = $inputField.closest(o.addErrClassTo);

      $errField.addClass(o.errorClass);
      $inputField.on('focus', function() {
        $(this).closest(o.addErrClassTo).removeClass(o.errorClass);
      });
    }
  });
};

#2

Oh, and this doesn’t yet return a true/false value yet (as it should). Still a work-in-progress.


#3

Hey, can you post your package.js file? This is where you control exports, file load order, etc.

Here’s an example package.js file: https://github.com/max-leportlabs/maxharris9-straightsix/blob/master/package.js


#4

Sure @maxharris9

Package.describe({
  name: 'captsaltyjack:form-validator',
  version: '1.0.0',
  // Brief, one-line summary of the package.
  summary: '',
  // URL to the Git repository containing the source code for this package.
  git: '',
  // By default, Meteor will default to using README.md for documentation.
  // To avoid submitting documentation, set this field to null.
  documentation: 'README.md'
});

Package.onUse(function(api) {
  api.versionsFrom('1.0.4.2');
  api.addFiles('form-validator.js');
  api.use(['jquery']);
  api.export('csjFormValidator', 'client');
});

Package.onTest(function(api) {
  api.use('tinytest');
  api.use('captsaltyjack:form-validator');
  api.addFiles('form-validator-tests.js');
});

#5

What you could do is to enclose the function within a namespace that will most likely be unique.

csFV = {}

csFV.csjFormValidator = function(form, options) {/* ... */}

api.export('csFV', 'client');

At this point you don’t worry about conflicting internal names that you want to expose. Therefore you can do this:

csFV.validateForm = function(form, options) {/* ... */}
csFV.validateField = function(field, options) {/* ... */}
csFV.validateButContinueAnyway = function(form, options) {/* ... */}