Skip to content

Instantly share code, notes, and snippets.

@lorenzoongithub
Created July 10, 2015 20:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lorenzoongithub/9640a1f6337f1af1cc66 to your computer and use it in GitHub Desktop.
Save lorenzoongithub/9640a1f6337f1af1cc66 to your computer and use it in GitHub Desktop.
//
// validate.js
// A declarative way of validating j
// javascript objects.
//
// This test was based on the example
// http://validatejs.org/#validate
//
load("http://cdnjs.cloudflare.com/ajax/libs/validate.js/0.8.0/validate.min.js");
constraints = {
username: {
presence: true,
exclusion: {
within: ["nicklas"],
message: "'%{value}' is not allowed"
}
},
password: {
presence: true,
length: {
minimum: 6,
message: "must be at least 6 characters"
}
}
};
x = validate({password: "bad"}, constraints);
x.username;
x.username[0];
if (x.username[0] !== "Username can't be blank") throw ""
x.password;
x.password[0];
if (x.password[0] !== "Password must be at least 6 characters") throw ""
x = validate({username: "nick", password: "better"}, constraints);
if (x !== undefined) throw "";
x = validate({username: "nicklas", password: "better"}, constraints);
x.username;
x.username[0];
if (x.username[0] !== "Username 'nicklas' is not allowed") throw ""
x = validate({password: "better"}, constraints, {fullMessages: false});
x.username;
x.username[0];
if (x.username[0] !== "can't be blank") throw "";
x = validate({}, constraints, {format: "flat"});
if (x[0] != "Username can't be blank") throw ""
if (x[1] != "Password can't be blank") throw ""
x = validate({username: "nicklas", password: "bad"}, constraints, {format: "detailed"});
x[0];
if (x[1].attribute != "password") throw "";
if (x[1].error != "Password must be at least 6 characters") throw "";
x[1].options;
if (x[1].options.minimum != 6) throw "";
if (x[1].options.message != "must be at least 6 characters") throw "";
if (x[1].validator != "length") throw "";
if (x[1].value != "bad") throw "";
x = validate({}, {username: {presence: {message: "^You must pick a username"}}});
x.username;
x.username[0];
if (x.username[0] != "You must pick a username") throw "";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment