Andrew
Andrew

Reputation: 15

Validate PHP form field if not left empty

I have a bit of a problem with my PHP form validation that I could use some help with.

I got an optional field which should be validated only if the user fills it, otherwise the form should be processed as normal. Here's the validation for the field:

if (!preg_match("/(0?\d|1[0-2]):(0\d|[0-5]\d) (AM|PM)/i", '$start')) :
        $errors->add('submit_error', __('<strong>ERROR</strong>: The time is incorrect', 'appthemes'));
        endif;

Might be simple, but at the moment I just can't get my head around how can I bypass the validation if the field is left empty. Any ideas?

Upvotes: 1

Views: 2779

Answers (4)

Ryan
Ryan

Reputation: 1888

Have you tried something like this:

if (!empty($_POST['field_name'])) {
if(!preg_match("/(0?\d|1[0-2]):(0\d|[0-5]\d) (AM|PM)/i", '$start')) :
    $errors->add('submit_error', __('<strong>ERROR</strong>: The time is incorrect', 'appthemes'));
}

It will first look at the state of the field then move to the validation if required.

EDIT Sorry, just realised there is an optimal way being:

if(!empty($start) && !preg_match("/(0?\d|1[0-2]):(0\d|[0-5]\d) (AM|PM)/i", '$start')) :
    $errors->add('submit_error', __('<strong>ERROR</strong>: The time is incorrect', 'appthemes'));
endif;

Why the !empty($start)? Because it is using the standard PHP function that defines if the value is present or not. Not 100% required but is best practice to use the empty() function when determining if a value exists or not.

Upvotes: 0

Emre Yazici
Emre Yazici

Reputation: 10174

Assuming your form data stored in $start :

if ($start && !preg_match("/(0?\d|1[0-2]):(0\d|[0-5]\d) (AM|PM)/i", '$start')) :
        $errors->add('submit_error', __('<strong>ERROR</strong>: The time is incorrect', 'appthemes'));
        endif;

Upvotes: 0

luxcem
luxcem

Reputation: 1854

if(!empty($your_field) && !preg_match(...))

PHP tests if the field is null before testing the regex. If the field is null PHP will jump to the next instruction.

Upvotes: 2

user456814
user456814

Reputation:

Wrap the rest of your code inside of this, it will only trigger if $start isn't empty,

if (trim($start)) {
    // put other code in here
}

Upvotes: 1

Related Questions