In order to set up this validation, which we're going to be doing in other places too like createMessage, we're going to create a separate utils file. In here, I'm going to call this validation.js and this is where we can put some validators that we're going to need throughout the project.
In this section we're going to create one called isRealString. This is going to verify that a value is of a type string and that it's not just a bunch of spaces; it actually has real characters inside it. We're going to set this equal to a function that takes a string. This is going to be the string we validate, and it's actually not going to be terribly difficult. We're going to return and we're going to return the following conditions. It'll return true if it is a real string and false if it's not. First up, we'll use typeof. This is going to get the type of the string variable, this needs to equal, in quotes, string:
var isRealString = (str) => {
return typeof str === 'string';
};
Now currently, this is going to return true for any string and false for any non-string value, but it does not take into account the spaces. What we're going to do is use the trim method available on strings which takes a string like this:
''
and converts it into a string like this, trimming all whitespace:
' '
If you pass in a string like, this it's going to convert it into a string like this:
' f '
trimming leading and trailing whitespace only:
'f'
It's not going to trim any interior spacing, so if I have f space r like this:
' f r '
I am still going to get that space between f and r, but all of the leading and trailing spaces are removed:
'f r'
We're going to use that like this:
var isRealString = (str) => {
return typeof str === 'string' && str.trim().length > 0;
};
After we call trim, we do need a length greater than 0, otherwise we have an empty string. This is going to be our isRealString function, and we're going to go ahead and export it real quickly, module.exports, setting it equal to an object where we set isRealString equal to the isRealString function:
var isRealString = (str) => {
return typeof str === 'string' && str.trim().length > 0;
};
module.exports = {isRealString};
Now I can go ahead and save this file. I'm also going to go ahead and inside server.js call the function.