Setting up form validation using Drupal "Form API Validation" module.
Form API validation is a contributed module which allows us to write the validation rules in custom forms, without the use of hook_validate/form_validate function
We can either the use the already defined rule constants such as 'numeric', 'decimal', 'alpha', 'length' etc or can create our own custom validation using the 'hook_fapi_validation_rules' function.
We just want the download and enable that module to our system and after that while adding the custom forms, we can add these rules to validate them.
For example, if want to validate only alpha characters with minimum 10 and maximum 50 characters inside a text field, put the rule like the following:
$form['name'] = array(
'#type' => 'textfield',
'#title' => t('Amount'),
'#required' => TRUE,
'#rules' => array(
'alpha',
'length[10, 50]'
),
);
Also if we need to restrict a field between a range of value we can use the 'range' rule. Format is range[
Similar to the rules, we can add filters also to a form element. For example, if we add a 'filter: numeric', then that field will accept only numeric characters. It will discard all other non-numeric characters.
There is a set of predefined filters such as 'numeric', 'trim', 'uppercase' etc and we can add our custom filters using hook_fapi_validation_filters.
This module also provides the option to alter the validation messages being displayed.
Refer the Drupal project page https://www.drupal.org/project/fapi_validation for more information.