Yannis
Yannis

Reputation: 6157

Re-use web models from Node.js in the client-side javascript code

In a project I m working on now I have some web models to represent form submission etc. For instance the login form (a pretty bad example) is as follows:

var revalidator = require('revalidator'); // A node.js module for validation

LoginForm = function(email, password) {
    this.Email = email;
    this.Password = password;
};

LoginForm.prototype.validate = function() {
  return revalidator.validate(this, {
    properties: {
        Email: {
          description: 'The email address provided is not valid',
          type: 'string',
          format: 'email',
          required: true
        },
        Password: {
          description: 'The password is not provided',
          type: 'string',
          required: true
        }
      }
  })
};

exports.LoginForm = LoginForm;

This works great currently in my current node.js setup, but I was wondering if there is any way I can reuse those models on the client-side javascript code. Any help would be really appreciated.

Upvotes: 0

Views: 404

Answers (1)

Sebastian vom Meer
Sebastian vom Meer

Reputation: 5241

Javascript is Javascript, you can share the code. You have to keep in mind that there are some differences between browsers and Node. If you want to share you code you must not use require and have to check if the export object exists before using it:

if(typeof exports === 'object'){
    exports.LoginForm = LoginForm;
} else {
    // your browser export
}

Upvotes: 2

Related Questions