I'm trying to keep my controller actions as lightweight as possible so i am implementing service layer. Now i've stucked with validation and sanitization. I know that validation should be done in service layer but what about sanitization? I would like to re-render the with the input data when there are validation errors.
//userService.js function
function register(data, callback) {
if (!data) {
return callback(new Error('Here some error...'));
}
/* Sanitize and validate the data */
/* Method #1 */
//If not valid then call back with validationErrors
if (notValid) {
return callback({
validationErrors: {
'username': 'Username is already in use.',
'email': 'Invalid characters.',
}
});
}
/* Method #2 */
if (notValid) {
return callback({
fields: {
//We put here a sanitized fields
},
validationErrors: {
'username': 'Username is already in use.',
'email': 'Invalid characters.',
}
});
}
};
//userController.js function
// GET/POST: /register
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) {
//Re-post the data so the user wont have to fill the form again
//Sanitize registerData variable here.
return response.render('register', {
error: error,
validationErrors: error.validationErrors
});
};
//User registered succesfully.
return response.render('registerSuccess');
});
return;
}
return response.render('register');
}
I see there 2 options.
- Call service function 'register' with raw POST data, sanitize and validate it then push back only validation errors. If there are validation errors then sanitize them in controller before rendering the view.
- Same as first one but we push back validation errors and sanitized fields.