I try to make my actions with the controller as easy as possible, so I implement the level of service. Now I stuck with validation and disinfection. I know that validation should be done at the service level, but what about sanitation? I want to redisplay them with input when there are validation errors.
function register(data, callback) {
if (!data) {
return callback(new Error('Here some error...'));
}
if (notValid) {
return callback({
validationErrors: {
'username': 'Username is already in use.',
'email': 'Invalid characters.',
}
});
}
if (notValid) {
return callback({
fields: {
},
validationErrors: {
'username': 'Username is already in use.',
'email': 'Invalid characters.',
}
});
}
};
function registerAction(request, response, next) {
if (request.method === 'POST') {
var registerData = {
username: request.body['username'],
password: request.body['password'],
email: request.body['email'],
firstName: request.body['firstName'],
lastName: request.body['lastName'],
};
register(registerData, function(error, someDataIfSucceed) {
if (error) {
return response.render('register', {
error: error,
validationErrors: error.validationErrors
});
};
return response.render('registerSuccess');
});
return;
}
return response.render('register');
}
I see 2 options there.
- The function to call "register" with raw POST data, disinfect and check, and then only check errors are discarded. If there are validation errors, then sanitize them in the controller before rendering the view.
- Same as the first, but we discard validation errors and sanitized fields.