我发现以下自定义验证方法比使用上述方法更有帮助。我想你最终会在某个时候想要自定义验证消息,对吧?
https://gist.github.com/basco-johnkevin/8436644
注意:我创建了一个名为 api/services/ValidationService.js 的文件,并将 gist 代码放在这里。这样我就不必在 Controller 中要求它了。
在控制器中:
create: function(req, res, next) {
//Create a User with the params sent from the signup form
//
User.create( req.params.all(), function userCreated( err, user ) {
// If there's an error
//
if(err) {
if(err.ValidationError) {
errors = ValidationService.transformValidation(User, err.ValidationError);
sails.log.warn(errors);
req.flash('error', errors);
}
// If error redirect back to the sign-up page
return res.redirect('/user/new');
}
// After successfully creating the user
// redirect the to the show action
res.json(user);
});
}
在我的用户模型中:
module.exports = {
schema: true,
attributes: {
name: {
type: 'string',
required: true
},
title: {
type: 'string'
},
email: {
type: 'string',
email: true,
required: true,
unique: true
},
encryptedPassword: {
type: 'string',
minLength: 6,
required: true
}
},
validation_messages: {
name: {
required: 'You must supply a valid name.'
},
email: {
email: 'You must supply a valid email address.',
required: 'You must supply a valid email address.',
unique: 'An account with this email address already exists.'
},
encryptedPassword: {
minLength: 'Your password must be atleast 6 characters long.',
required: 'You must supply a password that is atleast 6 characters long.'
}
}
};
这就是我最终在用户注册表单视图中看到的内容。嗯……一定有更好的办法。
<% if (req.session.flash && req.session.flash.error) { %>
<% var errors = req.flash('error') %>
<div class="alert alert-danger">
<button type="button" class="close" aria-hidden="true" data-dismiss="alert">×</button>
<ul>
<% Object.keys(errors).forEach(function(error) { %>
<% Object.keys(errors[error]).forEach(function(error_message) { %>
<% Object.keys(errors[error][error_message][0]).forEach(function(error_message_res) { %>
<li>
<%- errors[error][error_message][0][error_message_res] %>
</li>
<% }); %>
<% }); %>
<% }); %>
</ul>
</div>