Last active
March 19, 2016 01:27
-
-
Save leosilvadev/aef1ef012085f68552e8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var express = require('express'); | |
var expressValidator = require('express-validator'); | |
var app = express(); | |
var bodyParser = require('body-parser'); | |
app.use(bodyParser.json()); | |
app.use(expressValidator({ | |
customValidators: { | |
isPhones: function(values) { | |
var ehArray = Array.isArray(values); | |
if(!ehArray) return false; | |
var naoTemTelefone = values.length==0; | |
if(naoTemTelefone) return false; | |
var temTelefoneErrado = values.find(function(telefone){ | |
return !telefone.ddd || !telefone.numero; | |
}); | |
if(temTelefoneErrado) return false; | |
return true; | |
} | |
} | |
})); | |
var validaRegistroUsuario = function(req){ | |
req.checkBody('nome', 'Nome invalido').notEmpty(); | |
req.checkBody('email', 'Email invalido').notEmpty(); | |
req.checkBody('senha', 'Senha invalida').notEmpty(); | |
req.checkBody('url_foto', 'Senha invalida').notEmpty(); | |
req.checkBody('contato', 'Contato inválida').notEmpty(); | |
req.checkBody('contato.endereco', 'Endereco inválido').notEmpty(); | |
req.checkBody('contato.endereco.logradouro', 'Logradouro inválido').notEmpty(); | |
req.checkBody('contato.endereco.numero', 'Logradouro inválido').isInt(); | |
req.checkBody('contato.endereco.cep', 'Cep inválido').notEmpty(); | |
req.checkBody('contato.endereco.localizacao', 'Localizacao inválida').notEmpty(); | |
req.checkBody('contato.endereco.localizacao.lat', 'Latitude inválida').isFloat(); | |
req.checkBody('contato.endereco.localizacao.lon', 'Longitude inválida').isFloat(); | |
req.checkBody('contato.telefones', 'Ao menos um telefone deve ser informado').isPhones(); | |
} | |
app.post('/usuarios', function(req, res){ | |
validaRegistroUsuario(req); | |
var errors = req.validationErrors(); | |
if(errors){ | |
res.status(400).json(errors); | |
} else { | |
res.status(201).json({}) | |
} | |
}); | |
app.listen(8000, function(){ | |
console.log('App running...'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment