Search code examples
javascriptangularjsnode.jspugbrowserify

How to use Browserified npm package in Angular controller?


I've spent hours looking for a way to get this (or anything) working with Browserify, but could not find any tutorial or example that proved useful for my problem. Nearly all of them only show how to blundle your code, but none of them show how to actually access the code itself after it's been browserified. Maybe it's just something so straightforward that no one bothered to mention it, so my apologies if this is actually a silly question.

So, I have this application which implements username and password validation. I use the 'validator' npm package in combination with an OWASP recommended password complexity package to validate the input on the server side in node. From what I understand from the Browserify project, I should be able to browserify my module which require these packages, and load them on the client side too.

My customValidator.js module now looks like this:

var validator = require('validator')
var owasp = require('owasp-password-strength-test')

module.exports = {
  validator: validator,
  owasp: owasp,
  containsUsername: function(password, username) {
    return (new RegExp(username, 'i')).test(password)
  }
}

I want to use these functions on the client side too, preferably within AngularJS as I use Angular to manipulate the input fields based on the current (possibly invalid) input the user has provided.

Basically what I would like is symmetric input validation on both the client side as the server side by having access to the same module on both sides, which has been browserified for the client side.

I have ran the following command:

browserify --standalone customValidator.js > clientSideValidator.js

And then included the clientSideValidor.js script within my jade template

  script(src='clientSideValidator.js')

I have tried to access the functions in both Angular and a separate script within jade itself, but every function always returns undefined. How can I run something like 'validator.isAlphaNumeric($scope.username)' in my client side code?


Solution

  • You need to give browserify a name to export everything to.

    Try running this and replace 'myModuleName' with what you would like to name it

    $ browserify customValidator.js --standalone myModuleName > clientSideValidator.js