Skip to content

Instantly share code, notes, and snippets.

@PaulBGD
Last active December 5, 2015 23:15
Show Gist options
  • Save PaulBGD/1320e0e819f772559db9 to your computer and use it in GitHub Desktop.
Save PaulBGD/1320e0e819f772559db9 to your computer and use it in GitHub Desktop.
Artisan Validator TypeScript Definition + Example
/// <reference path="../bluebird/bluebird.d.ts" />
declare module ArtisanValidator {
class Validator<R> {
try(checking: any, rules: R): Promise<ValidatorResult<R>>;
validators: ArtisanValidator.Validators;
}
interface ValidatorResult<R> {
failed: boolean;
passed: boolean;
errors: R;
}
interface Validators {
add(func: (...any) => boolean);
}
}
declare module 'artisan-validator' {
interface ArtisanConstructor {
<R>(): ArtisanValidator.Validator<R>;
}
var v: ArtisanConstructor;
export = v;
}
/// <reference path="../../typings/tsd.d.ts" />
import {Router, Request, Response} from 'express';
import * as ArtisanValidator from 'artisan-validator';
import * as phonelib from 'phone';
let API: Router = Router();
interface ValidatorRules {
email: string[];
password: string[];
contact: string[];
contactEmail: string[];
contactNumber: string[];
}
let rules: ValidatorRules = {
email: ['required', 'between: 4, 50', 'email'],
password: ['required', 'between: 6, 50'],
contact: ['required', 'between: 6, 32'],
contactEmail: ['required', 'between: 4, 50', 'email'],
contactNumber: ['required', 'between: 4, 15', 'phone']
};
let validator: ArtisanValidator.Validator<ValidatorRules> = ArtisanValidator<ValidatorRules>();
validator.validators.add(function phone(num: string): boolean {
return phonelib(num, 'UK').length > 0;
});
API.post('/register', (req: Request, res: Response) => {
validator.try(req.body, rules).then((result: ArtisanValidator.ValidatorResult<ValidatorRules>) => {
if (result.failed) {
return res.json({error: true, errors: result.errors});
}
// todo register
res.json({error: false});
});
});
export default API;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment