5
\$\begingroup\$
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?

\$\endgroup\$

2 Answers 2

1
\$\begingroup\$

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.

\$\endgroup\$
1
  • \$\begingroup\$ thanks, I adopted this form. It is indeed more clear and succinct. \$\endgroup\$ Commented Feb 15, 2017 at 10:22
1
\$\begingroup\$

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.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.