# Validation sequence

if ( ! empty( $form[ 'email' ] ) ) {$validator = v::email()->validate( $form[ 'email' ] ); if ($validator === false ) {
$formErrorBag[ 'email' ] = "Please enter a valid email"; } } else {$formErrorBag[ 'email' ] = "This field is required";
}


Here is code that handles email validation. There are several of these to handle various fields (username, passwords....).

This code is working, but I find it verbose. Would there be a more concise way of achieving the same?

Just looking at the ifs without more context, this would be more readable:

if (empty($form['email'])) {$formErrorBag[ 'email' ] = "This field is required";
} else if (v::email()->validate($form['email']) === false) {$formErrorBag[ 'email' ] = "Please enter a valid email";
}


Generally with ifs, you should try to handle the shortest case (the one with the fewest lines) first. When doing validation, it's also always good to handle the negative case first.

Depending on the exact context and framework, different solutions may be even more sensible.

• thanks, I adopted this form. It is indeed more clear and succinct. Feb 15, 2017 at 10:22

You may consider PHP's filter_input_array() function which would allow you to define a validation configuration array and then execute all validation rules against input parameters in one pass.

Alternately you might consider validation libraries common to most of the popular PHP frameworks.