2.3. Data validation

It is very important that every function exposed by each module validates its input data correctly. All of the arguments need to be checked, if this wasn't done a module could save syntactically wrong values in its configuration, and the underlying service would behave in an unpredictable way with the configuration file generated by the module. This also helps find bugs in the GUI front-end, and any other code that uses the module.

The EBox::Validate perl module provides a bunch of functions to validate different types of data. All of this functions work the same way, their first argument is the value that's going to be checked. They return true if the value is correct, undef if it's not:

Example 2.5. Using data validation functions

use EBox::Validate qw(:all);

my $ip = '192.168.0.1';

unless (checkIP($ip))
	print STDERR "$ip is invalid.\n";
}

The usual thing to do if an argument is incorrect is to throw an exception. And most of the time the incorrect value will be an user-supplied one. For this reasons, all the functions in EBox::Validate provide an easy mechanism for throwing EBox::External exceptions. All you have to do is pass one more argument to them, with a name or description for the value you are trying to check. If you pass that argument and the validation fails, an exception will be thrown with a message indicating the name of the wrong field:

Example 2.6. Using data validation functions with automatic error handling

checkIP($ip, 'IP address');

If you don't want an exception to be thrown, or if you want to throw a different kind of exception, just do not pass the last argument and handle the error yourself.