Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var any = (...vs) => ["any", ...vs]
- var all = (...vs) => ["all", ...vs]
- var prop = (msg, p) => ["prop", msg, p]
- var describe = (message, v) => ["describe", message, v]
- var fields = (scheme) => ["fields", scheme]
- var not = (msg, v) => ["not", msg, v]
- var matches = (string) =>
- prop("matches " + string, (input) =>
- input.match(string))
- var length = (msg, lenPred) =>
- map((str) => str.length, prop(msg, lenPred))
- var map = (f, v) => ["map", f, v]
- var validateWith = (template, object) => {
- let [head, ...tail] = template
- switch (head) {
- case "all": {
- let errors = tail.
- map(t => validateWith(t, object)).
- filter(x => x)
- return errors.length? ["all", ...errors] : null
- }
- case "any": {
- var acc = []
- for (var i = 0; i < tail.length; i++) {
- let sub = validateWith(tail[i], object)
- if (!sub)
- return null
- acc.push(sub)
- }
- return ["any", ...acc]
- }
- case "prop": {
- let [msg, prop] = tail
- return prop(object) ? null : msg
- }
- case "describe": {
- let [msg, v] = tail
- let sub = validateWith(v, object)
- return sub ? msg : null
- }
- case "fields": {
- let [o] = tail
- var acc = {}
- var hasErrors = false
- for (var key in o) {
- let sub = validateWith(o[key], object[key])
- if (sub) {
- acc[key] = sub
- hasErrors = true
- }
- }
- return hasErrors? ["fields", acc] : null
- }
- case "not": {
- let [msg, v] = tail
- let sub = validateWith(v, object)
- return sub? null: msg;
- }
- case "map": {
- let [f, v] = tail
- let projected = f(object)
- return validateWith(v, projected)
- }
- }
- }
- var makeValidatorFromScheme = (scheme) => (o) =>
- validateWith(scheme, o)
- var validateUser = makeValidatorFromScheme(
- fields({
- email: describe("proper email",
- matches(".*@.*")
- ),
- name: all(
- describe("contains only alphanumeric and '-'",
- matches("[A-Za-z0-9-]*")
- ),
- length(">= 3 chars", (len) => len >= 3),
- length("<= 20 chars", (len) => len <= 20),
- describe("no shit",
- not("bad word", matches("shit|crap"))
- )
- ),
- password: all(
- describe("has lower chars", matches("[a-z]")),
- describe("has capital chars", matches("[A-Z]")),
- describe("has numeric chars", matches("[0-9]")),
- length(">= 8 chars", (len) => len >= 8)
- )
- })
- )
- // validator will produce "null" on success and non-null structure on failure
- console.log(validateUser({
- email: "hui-mail.ru",
- name: "crappy-nickname",
- password: "lol567"
- }));
- // Will print:
- // [ 'fields',
- // { name: [ 'all', 'no shit' ],
- // password: [ 'all', 'has capital chars', '>= 8 chars' ] } ]
- console.log(validateUser({
- email: "hui@mail.ru",
- name: "cparry-nickname",
- password: "loLd5671"
- }));
- // Will print:
- // null
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement