Add scripts to create myops-getqueryview:
[myops.git] / web / query / lib / validate.js
1 // a library for validations
2 // over time we expect to extract more helpers and move them here.
3 exports.init = function(newDoc, oldDoc, userCtx, secObj) {
4   var v = {};
5   
6   v.forbidden = function(message) {    
7     throw({forbidden : message});
8   };
9
10   v.unauthorized = function(message) {
11     throw({unauthorized : message});
12   };
13
14   v.assert = function(should, message) {
15     if (!should) v.forbidden(message);
16   }
17   
18   v.isAdmin = function() {
19     return userCtx.roles.indexOf('_admin') != -1
20   };
21
22   v.require = function() {
23     for (var i=0; i < arguments.length; i++) {
24       var field = arguments[i];
25       message = "The '"+field+"' field is required.";
26       if (typeof newDoc[field] == "undefined") v.forbidden(message);
27     };
28   };
29
30   v.unchanged = function(field) {
31     if (oldDoc && oldDoc[field] != newDoc[field]) 
32       v.forbidden("You may not change the '"+field+"' field.");
33   };
34
35   v.matches = function(field, regex, message) {
36     if (!newDoc[field].match(regex)) {
37       message = message || "Format of '"+field+"' field is invalid.";
38       v.forbidden(message);    
39     }
40   };
41
42   // this ensures that the date will be UTC, parseable, and collate correctly
43   v.dateFormat = function(field) {
44     message = "Sorry, '"+field+"' is not a valid date format. Try: 2010-02-24T17:00:03.432Z";
45     v.matches(field, /\d{4}\-\d{2}\-\d{2}T\d{2}:\d{2}:\d{2}(\.\d*)?Z/, message);
46   }
47   
48   return v;
49 };