Reputation: 21333
I have four fields. Lets call them a
, b
, c
and d
. I need to validate them.
Error is when:
Error is not when:
Any neat solution here? Thanks in advice.
Edit:
Only relationships are that all four variables are prefixed with event_
. It gives me event_name
, event_description
etc..
Edit #2:
At the moment I have something like...
if (
!empty($values['event_date'])
&& !empty($values['event_time'])
&& !empty($values['event_name'])
&& !empty($values['event_description'])
) {
It checks that all fields are filled up and then, if that's true, adds event.
As I said before, I need to display user-friendly error when some field isn't filled up (for example, user had forgot to enter description). Anyway, when all fields are filled up (it means - all okay) or when no fields are filled up (it means - user ignores event adding and don't want to add one) - no error should be displayed.
I could write code with 16 'if' statements, but isn't there any better way? :)
Upvotes: 1
Views: 440
Reputation: 476
This isn't beautiful, but as long as you have something unique about the fields you want to check (such as "event_..."), you could loop through the variable array ($values, $_POST, etc) and check only the fields that matter. Then, you can easily check for an all or none situation.
Here is a quick example:
$total = 0;
$filled = 0;
foreach($values as $field => $val) {
if(strpos($field,'event_') === 0) {
$total++;
if( ! empty($val)) {
$filled++;
}
}
}
if($filled == 0 OR $total == $filled) {
//PASS VALIDATION
} else {
//FAIL VALIDATION
}
Upvotes: 1
Reputation: 498
Is there a relationship between one of the entered values and the none entered values?? could you just parse it as an empty value?
if ( ! isset($post->a) ) $post->a = '';
Upvotes: 0