Merge pull request #2716 from strongloop/feature/isemail-2x

Rework email validation to use isemail
This commit is contained in:
Miroslav Bajtoš 2016-09-06 13:52:09 +02:00 committed by GitHub
commit 74deec8142
3 changed files with 28 additions and 9 deletions

View File

@ -9,6 +9,7 @@
var g = require('strong-globalize')();
var isEmail = require('isemail');
var loopback = require('../../lib/loopback');
var utils = require('../../lib/utils');
var path = require('path');
@ -735,10 +736,9 @@ module.exports = function(User) {
assert(loopback.AccessToken, 'AccessToken model must be defined before User model');
UserModel.accessToken = loopback.AccessToken;
// email validation regex
var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
UserModel.validatesFormatOf('email', {with: re, message: g.f('Must provide a valid email')});
UserModel.validate('email', emailValidator, {
message: g.f('Must provide a valid email')
});
// FIXME: We need to add support for uniqueness of composite keys in juggler
if (!(UserModel.settings.realmRequired || UserModel.settings.realmDelimiter)) {
@ -756,3 +756,14 @@ module.exports = function(User) {
User.setup();
};
function emailValidator(err, done) {
var value = this.email;
if (value == null)
return;
if (typeof value !== 'string')
return err('string');
if (value === '') return;
if (!isEmail(value))
return err('email');
}

View File

@ -43,6 +43,7 @@
"errorhandler": "^1.3.4",
"express": "^4.12.2",
"inflection": "^1.6.0",
"isemail": "^1.2.0",
"loopback-connector-remote": "^1.0.3",
"loopback-context": "^1.0.0",
"loopback-phase": "^1.2.0",

View File

@ -132,10 +132,7 @@ describe('User', function() {
assert.equal(err.name, 'ValidationError');
assert.equal(err.statusCode, 422);
assert.equal(err.details.context, User.modelName);
assert.deepEqual(err.details.codes.email, [
'presence',
'format.null'
]);
assert.deepEqual(err.details.codes.email, ['presence']);
done();
});
@ -155,11 +152,21 @@ describe('User', function() {
it('Requires a valid email', function(done) {
User.create({email: 'foo@', password: '123'}, function(err) {
assert(err);
assert.equal(err.name, 'ValidationError');
assert.equal(err.statusCode, 422);
assert.equal(err.details.context, User.modelName);
assert.deepEqual(err.details.codes.email, ['custom.email']);
done();
});
});
it('allows TLD domains in email', function() {
return User.create({
email: 'local@com',
password: '123'
});
});
it('Requires a unique email', function(done) {
User.create({email: 'a@b.com', password: 'foobar'}, function() {
User.create({email: 'a@b.com', password: 'batbaz'}, function(err) {