Skip to content

Commit

Permalink
feat(members): more validations
Browse files Browse the repository at this point in the history
  • Loading branch information
serge1peshcoff committed Feb 3, 2020
1 parent 0130935 commit 0630881
Showing 1 changed file with 25 additions and 0 deletions.
25 changes: 25 additions & 0 deletions models/User.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,11 @@ const User = sequelize.define('user', {
defaultValue: '',
validate: {
notEmpty: { msg: 'Username should be set.' },
isValid(value) {
if (!/^[a-zA-Z0-9\._-]*$/.test(value)) {
throw new Error('Username should only contain letters, numbers, dots, underscores and dashes.');
}
}
},
unique: true
},
Expand Down Expand Up @@ -53,6 +58,11 @@ const User = sequelize.define('user', {
defaultValue: '',
validate: {
notEmpty: { msg: 'First name should be set.' },
isValid(value) {
if (!new RegExp('^[\\p{L} -]*$', 'u').test(value)) {
throw new Error('First name should only contain letters, spaces and dashes.');
}
}
}
},
last_name: {
Expand All @@ -61,6 +71,11 @@ const User = sequelize.define('user', {
defaultValue: '',
validate: {
notEmpty: { msg: 'Last name should be set.' },
isValid(value) {
if (!new RegExp('^[\\p{L} -]*$', 'u').test(value)) {
throw new Error('Last name should only contain letters, spaces and dashes.');
}
}
}
},
date_of_birth: {
Expand Down Expand Up @@ -105,6 +120,16 @@ const User = sequelize.define('user', {
}
});

User.beforeValidate(async (user) => {
if (user.changed('password')) {
user.password = await bcrypt.hash(user.password, config.salt_rounds);
}

// skipping these fields if they are unset, will catch it later.
if (typeof user.email === 'string') user.email = user.email.toLowerCase().trim();
if (typeof user.username === 'string') user.username = user.username.toLowerCase().trim();
});

User.afterValidate(async (user) => {
if (user.changed('password')) {
user.password = await bcrypt.hash(user.password, config.salt_rounds);
Expand Down

0 comments on commit 0630881

Please sign in to comment.