I am coding a site where users submit sporting events.
When submitting an event there are a lot of fields that need to be validated.
This is the method I wrote to valid the fields:
class event{
private $dbh;
private $post_data;
public function __construct($post_data, PDO $dbh){
$this->dbh = $dbh;
$this->post_data = array_map('trim', $post_data);
}
// long ass method that checks all the input fields are valid
public function checkValidInput(){
if(!empty($this->post_data['event-name']) && (strlen($this->post_data['event-name']) < 101)){
if(!empty($this->post_data['event-description']) && (strlen($this->post_data['event-description']) < 2001)){
if(!empty($this->post_data['event-location-name']) && (strlen($this->post_data['event-location-name']) < 51)){
if(!empty($this->post_data['event-location-town']) && (strlen($this->post_data['event-location-town']) < 21)){
if(isset($this->post_data['event-county'])){
if(!empty($this->post_data['event-postcode']) && (strlen($this->post_data['event-postcode']) < 21)){
if(isset($this->post_data['event-age-restriction'])){
if(!empty($this->post_data['event-booking-address']) && (strlen($this->post_data['event-booking-address']) < 301)){
if(!empty($this->post_data['event-organiser']) && ($this->post_data['event-organiser'] < 51) ){
if(isset($this->post_data['event-select-difficulty'])){
if(isset($this->post_data['event-select-type'])){
if(isset($this->post_data['event-select-environment'])){
if(isset($this->post_data['event-select-traffic'])){
return TRUE;
}else{
throw new Exception('Please select the type of traffic.');
}
}else{
throw new Exception('Please select the type of environment.');
}
}else{
throw new Exception('Please select the type of event.');
}
}else{
throw new Exception('Please select a difficulty rating for this event.');
}
}else{
throw new Exception('Please enter an organiser name that is no longer than 50 characters.');
}
}else{
throw new Exception('Please enter the booking page url for this event. Or the home website url.');
}
}else{
throw new Exception('Please select appropriate age restriction.');
}
}else{
throw new Exception('Please enter a location post code that is no longer than 10 characters.');
}
}else{
throw new Exception('Please select a location county.');
}
}else{
throw new Exception('Please enter a location town name that is no longer than 20 characters.');
}
}else{
throw new Exception('Please enter a location name that is no longer than 50 characters.');
}
}else{
throw new Exception('Please enter a description that is no longer than 2000 characters.');
}
}else{
throw new Exception('Please enter a name that is no longer than 100 characters.');
}
}
}
As you can see its a pretty big, ugly looking block of code.
Is there a prettier way of writing this that could half the amount of code?