Skip to content
This repository was archived by the owner on May 14, 2023. It is now read-only.

Examples

Raphael Pigulla edited this page Jun 3, 2014 · 6 revisions

Examples

For illustrative purposes we have compiled a few more complex examples.

Example: Log Messages

lewd([{
    timestamp: lewd.isoDateTime(),
    level: lewd('verbose', 'info', 'warning', 'error'),
    message: String
}]);

Validates the following JSON data:

[
    { "timestamp": "2014-05-27T20:37:52.630Z", "level": "warn", "message": "Disk is full" },
    { "timestamp": "2014-05-27T20:37:32.190Z", "level": "info", "message": "System is online" }
]

Example: Address

lewd.object({
    firstName: lewd.required(String),
    lastName: lewd.required(String),
    title: lewd('Mr', 'Mrs'),
    dob: lewd.isoDateTime().coerce(),
    city: String,
    zip: lewd.all(Number, lewd.range({ min: 1000, max: 99999 })),
    street: String
}, { 
    byDefault: 'optional'
});

Validates the following JSON data:

{
    "firstName": "Foo",
    "lastName": "Bar",
    "dob": "1977-06-25T00:00:00.000Z",  // this will get transformed into a Date object
    "title": "Mr",
    "zip": 12345
}

There is no concise way to use lewd to validate that an entry either contains both zip and city or neither, this should be handled by your application.


Example: Book

For clarity and reusability you can split the definition up into smaller parts:

var positiveInt = lewd.all(lewd.integer(), lewd.range({ min: 1 })),
    chapter = lewd({
        title: String,
        pages: positiveInt,
        footnotes: lewd.optional([{
            id: positiveInt,
            text: String
        }])
    });

var book = lewd({
    title: String,
    price: lewd.optional(lewd.all(Number, lewd.range({ min: 0 }))),
    hasIndex: Boolean,
    chapters: lewd.all([chapter], lewd.len({ min: 2 }))
})

Does not validate the following JSON data because there are too few chapters:

{
    "title": "lewd for hackers",
    "hasIndex": true,
    "chapters": [
        {
            "title": "Introduction",
            "pages": 4
        }, {
            "title": "First Steps",
            "pages": 7,
            "footnotes": [
                { "id": 1, "text": "..." },
                { "id": 21, "text": "..." }
            ]
        }
    ]
}

Clone this wiki locally