I am trying to check a form field for a maxlength.
When I initially submit the form with a string of characters over the maximum
the error is detected and the warning is displayed, however if I fill in the other form fields,
including the field which still has too many characters, and submit the form again, the maxlength is not detected and the form submits.

function filterName($field){
    // Sanitize user name
    $field = filter_var(trim($field), FILTER_SANITIZE_STRING);

// Validate user name
if(filter_var($field, FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/^[a-zA-Z\s]+/")))){
    return $field;
}else{
    return FALSE;
}
  if(empty($_POST["friend"])){
        $nameErr1 = 'Please enter your friend\'s name.';

}elseif(strlen($_POST["friend"]) > 30){

$namelengthError1 = "The number of character exceeds the maximum limit";	
	}
	else{

    $friendsname = filterName($_POST["friend"]);
    if($friendsname == FALSE){
        $nameErr2 = 'Please enter a valid name.';
    }
}
<span class="errors"><?php if(isset($nameErr1)){echo $nameErr1;} if(isset($namelengthError1)){echo $namelengthError1;} ?></span>
  <label for="friend">Your friend's name:</label>
  <input type="text" name="friend" id="friend" class="inputfield" value="<?php if(isset($friendsname)){echo htmlspecialchars($friendsname, ENT_QUOTES);} ?>">
</p>

    however if I fill in the other form fields,
    including the field which still has too many characters, and submit the form again, the maxlength is not detected and the form submits.

    You probably have an error in your program logic, i.e. reusing variables. It would take having enough of your code that reproduces the problem to help find specifically what's causing the problem.

    I your last thread, someone suggested using an array to hold the error messages. This will simplify your code and make troubleshooting the problem easier. You can use print_r() on the array at any point to see all the errors it holds. This will also eliminate the need to keep adding discrete variables in multiple places in your code. Note: there can only be one validation error for each form field at any one time and you are not even displaying the third possible error in the posted code. Using an array as suggested will result in only one entry in the array for each form field, which will also make it easier to display any result.

    You also have a problem in that if a FALSE value is returned by the filterName() function, you will repopulate the form field with nothing. This will make the user keep reentering the value, when all they probably need to do is correct one or two characters in it. You should also tell the user exactly what is invalid about what they entered, so that they can correct it. Don't leave a user guessing what they need to do or what they did wrong.

    Edit: you should also be validating a trimmed version of the input data. If someone manages to add a space, tab, or new-line character, before or after the value, your empty() and maximum length tests won't produce an accurate result.

      7 days later

      I have managed to add and remove validation rules via a class,
      however I can only display the errors in their raw format using print_r.

      
      Array
      (
          [friend] => Array
              (
                  [0] => The friend field is required
                  [1] => The friend field must be a minimum of 3 length
                  [2] => The friend field must contain only letters or numbers
              )
      
      [to] => Array
          (
              [0] => The to field is required
              [1] => That is not a valid email address
          )
      
      [you] => Array
          (
              [0] => The you field is required
              [1] => The you field must be a minimum of 3 length
              [2] => The you field must contain only letters or numbers
          )
      
      [sender] => Array
          (
              [0] => The sender field is required
              [1] => That is not a valid email address
          )
      
      )
      
      

      I think the implode function is required to display errors as a bulleted list,
      however I'm not sure how to apply it to the method calls etc.

      echo '<pre>', print_r($validation->errors()->all()), '</pre>';

      $errorHandler = new ErrorHandler;
      
      $validator = new Validator($errorHandler);
      
      $validation = $validator->check($_POST, [
      
      'friend' => [
      
      'required' => true,
      'maxlength' => 20,
      'minlength' => 3,
      'alnum' => true
      
      ],
      
      'to' => [
      
      'required' => true,
      'maxlength' => 255,
      'email' => true
      
      ],
      
      'you' => [
      
      'required' => true,
      'maxlength' => 20,
      'minlength' => 3,
      'alnum' => true
      
      ],
      
      'sender' => [
      
      'required' => true,
      'maxlength' => 255,
      'email' => true
      
      ]
      
      ]);
      
      if($validation->fails()){
      
      echo '<pre>', print_r($validation->errors()->all()), '</pre>';
      
      }

        This is the code from the form validation class.

        <?php 
        
        class Validator {
        
        protected $errorHandler;	
        protected $rules = ['required', 'minlength', 'maxlength', 'email', 'alnum'];
        
        public $messages = [
        
        'required' => 'The :field field is required',
        'minlength' => 'The :field field must be a minimum of :satisifer length',
        'maxlength' => 'The :field field must be a maximum of :satisifer length',
        'email' => 'That is not a valid email address',
        'alnum' => 'The :field field must contain only letters or numbers'
        
        ];
        
        public function __construct(ErrorHandler $errorHandler){
        
        $this->errorHandler = $errorHandler;
        
        }
        public function check($items, $rules){
        foreach($items as $item => $value){
        if(in_array($item, array_keys($rules))){
        	$this->validate([
        
        'field' => $item,
        'value' => $value,
        'rules' => $rules[$item]
        
        
        ]);
        
        }
        }
        return $this;
        }	
        
        public function fails(){
        
        return $this->errorHandler->hasErrors();
        
        }
        
        
        public function errors(){
        
        return $this->errorHandler;
        
        }
        
        protected function validate($item){
        
        $field = $item['field'];
        
        foreach($item['rules'] as $rule => $satisifer){
        
        	if(in_array($rule, $this->rules)){
        
        		if(!call_user_func_array([$this, $rule], [$field, $item['value'], $satisifer])){
        
        			$this->errorHandler->addError(
        			str_replace([':field', ':satisifer'], [$field, $satisifer], $this->messages[$rule]),
        			$field
        			);
        			}
        		}
        	}
        
        }
        
        protected function required($field, $value, $satisifer){
        
        return !empty(trim($value));
        
        }
        
        protected function minlength($field, $value, $satisifer){
        
        return strlen($value)>=$satisifer;
        
        }
        
        protected function maxlength($field, $value, $satisifer){
        
        return strlen($value)<=$satisifer;
        
        }
        
        protected function email($field, $value, $satisifer){
        
        return filter_var($value, FILTER_VALIDATE_EMAIL);
        
        }
        
        protected function alnum($field, $value, $satisifer){
        
        	//Add any character to be allowed $isValid = array('-', '_'); 
        
        	  $isValid = array(' ');
        
        return ctype_alnum(str_replace($isValid, '', $value));
        
        }
        
        }

        This is the error handler code

        class ErrorHandler {
        
        protected $errors = [];
        public function addError($error, $key = NULL){
        
        	if($key){
        		$this->errors[$key][] = $error;
        		}else{
        
        		$this->errors[] = $error;	
        			}
        
        	}
        public function all($key = NULL){
        
        	return isset($this->errors[$key]) ? $this->errors[$key] : $this->errors;
        
        	}
        
        public function hasErrors(){
        
        	return count($this->all()) ? true : false;
        
        	}
        
        public function first($key){
        
        		return isset($this->all()[$key][0]) ? $this->all()[$key][0] : false;
        
        	}
        
        }
        

        As previously stated I can output the errors via print_r

        if($validation->fails()){

        echo '<pre>', print_r($validation->errors()->all()), '</pre>'; 

        }

        Array
        (
            [friend] => Array
                (
                    [0] => The friend field is required
                    [1] => The friend field must be a minimum of 3 length
                    [2] => The friend field must contain only letters or numbers
                )
        
        [to] => Array
            (
                [0] => The to field is required
                [1] => That is not a valid email address
            )
        
        [you] => Array
            (
                [0] => The you field is required
                [1] => The you field must be a minimum of 3 length
                [2] => The you field must contain only letters or numbers
            )
        
        [sender] => Array
            (
                [0] => The sender field is required
                [1] => That is not a valid email address
            )
        
        )

        I would like to know how to display the errors as html.
        Any help welcome!

        $errorHandler = new ErrorHandler; 
        
        $validator = new Validator($errorHandler); 
        
        $validation = $validator->check($_POST, [ 
        
        'friend' => [ 
        
        'required' => true, 
        'maxlength' => 20, 
        'minlength' => 3, 
        'alnum' => true 
        
        ], 
        
        'to' => [ 
        
        'required' => true, 
        'maxlength' => 255, 
        'email' => true 
        
        ], 
        
        'you' => [ 
        
        'required' => true, 
        'maxlength' => 20, 
        'minlength' => 3, 
        'alnum' => true 
        
        ], 
        
        'sender' => [ 
        
        'required' => true, 
        'maxlength' => 255, 
        'email' => true 
        
        ] 
        
        ]); 
        
        if($validation->fails()){ 
        
        echo '<pre>', print_r($validation->errors()->all()), '</pre>'; 
        
        }  

          I managed to display the errors as required.

          Initially I tried to implode $myerrors = $validation->errors()->all();

          $newerrors = implode(' ', $myerrors);

          However this returned Array Array Array Array

          I then tried the array_map() function which sends each value of an array to a user-made function,
          and returns an array with new values, given by the user-made function.

          This output the errors as in one continuous string

          The Friends Name field is required The Friends Email Address field is required The Your Name field is required The Your Email Address field is required

          To display the errors as a bulleted list I

          implode('-', array_map ......

          Then exploded the string back to an array

          explode('-', $newerrors);

          Then looped through the array using a foreach loop

          foreach($newer as $keys){

          The errors now display as a bulleted list

          [LIST]

          The Friends Name field is required
          [] The Friends Email Address field is required
          [*] The Your Name field is required
          [] The Your Email Address field is required
          [/B]
          [*]
          [/LIST]

          if($validation->fails()){
          
          $myerrors = $validation->errors()->all();
          
          $newerrors = implode('-', array_map(function($el){ return $el[0]; }, $myerrors));
          
          $newer = explode('-', $newerrors); 
          
          echo '<div class="validation_errors"><ul>';
          
          foreach($newer as $keys){
          	echo "<li>" . $keys . "</li>";
          
          	}
          	echo '</ul></div>';

            Just found out, the implode and explode I used are redundant,
            I should have simply used -

             foreach($myerrors as $error){   
            
            echo "<li>" . $error[0] . "</li>";   
            
            
               }   
            echo '</ul></div>';

            Looks like I still have much to learn!

            maxwell@;11056645 wrote:

            I managed to display the errors as required.

            Initially I tried to implode $myerrors = $validation->errors()->all();

            $newerrors = implode(' ', $myerrors);

            However this returned Array Array Array Array

            I then tried the array_map() function which sends each value of an array to a user-made function,
            and returns an array with new values, given by the user-made function.

            This output the errors as in one continuous string

            The Friends Name field is required The Friends Email Address field is required The Your Name field is required The Your Email Address field is required

            To display the errors as a bulleted list I

            implode('-', array_map ......

            Then exploded the string back to an array

            explode('-', $newerrors);

            Then looped through the array using a foreach loop

            foreach($newer as $keys){

            The errors now display as a bulleted list

            [LIST]

            The Friends Name field is required
            [] The Friends Email Address field is required
            [*] The Your Name field is required
            [] The Your Email Address field is required
            [/B]
            [*]
            [/LIST]

            if($validation->fails()){
            
            $myerrors = $validation->errors()->all();
            	}
            	echo '</ul></div>';

            $newerrors = implode('-', array_map(function($el){ return $el[0]; }, $myerrors));

            $newer = explode('-', $newerrors);

            echo '<div class="validation_errors"><ul>';

            foreach($newer as $keys){
            echo "<li>" . $keys . "</li>";

              Write a Reply...