Symfony - Validation


Advertisements


Validation is the most important aspect while designing an application. It validates the incoming data. This chapter explains about form validation in detail.

Validation Constraints

The validator is designed to validate objects against constraints. If you validate an object, simply map one or more constraints to its class and then pass it to the validator service. By default, when validating an object all constraints of the corresponding class will be checked to see whether or not they actually pass. Symfony supports the following notable validation constraints.

NotBlank

Validates that a property is not blank. Its syntax is as follows −

namespace AppBundle\Entity; 
use Symfony\Component\Validator\Constraints as Assert; 

class Student { 
   /** 
      * @Assert\NotBlank() 
   */ 
   protected $studentName; 
} 

This NotBlank constraint ensures that studentName property should not blank.

NotNull

Validates that a value is not strictly equal to null. Its syntax is as follows −

namespace AppBundle\Entity; 
use Symfony\Component\Validator\Constraints as Assert; 

class Student { 
   /** 
      * @Assert\NotNull() 
   */ 
   protected $studentName; 
} 

Email

Validates that a value is a valid email address. Its syntax is as follows −

namespace AppBundle\Entity; 
use Symfony\Component\Validator\Constraints as Assert; 

class Student { 
   /** 
      * @Assert\Email( 
         * message = "The email '{{ value }}' is not a valid email.", 
         * checkMX = true 
      * ) 
   */ 
   protected $email; 
}

IsNull

Validates that a value is exactly equal to null. Its syntax is as follows −

namespace AppBundle\Entity; 
use Symfony\Component\Validator\Constraints as Assert; 

class Student { 
   /** 
      * @Assert\IsNull() 
   */ 
   protected $studentName; 
}

Length

Validates that a given string length is between some minimum and maximum value. Its syntax is as follows −

namespace AppBundle\Entity; 
use Symfony\Component\Validator\Constraints as Assert; 

class Student { 
   /**
      * @Assert\Length( 
         * min = 5, 
         * max = 25, 
         * minMessage = "Your first name must be at least {{ limit }} characters long", 
         * maxMessage = "Your first name cannot be longer than {{ limit }} characters" 
      * ) 
   */ 
   protected $studentName; 
}

Range

Validates that a given number is between some minimum and maximum number. Its syntax is as follows −

namespace AppBundle\Entity; 
use Symfony\Component\Validator\Constraints as Assert; 
class Student { 
   /** 
      * @Assert\Range( 
         * min = 40, 
         * max = 100, 
         * minMessage = "You must be at least {{ limit }} marks”, 
         * maxMessage = "Your maximum {{ limit }} marks” 
      * ) 
   */ 
   protected $marks; 
} 

Date

Validates that a value is a valid date. It follows a valid YYYY-MM-DD format. Its syntax is as follows −

namespace AppBundle\Entity; 
use Symfony\Component\Validator\Constraints as Assert; 

class Student { 
   /** 
      * @Assert\Date() 
   */ 
   protected $joinedAt; 
} 

Choice

This constraint is used to ensure that the given value is one of a given set of valid choices. It can also be used to validate that each item in an array of items is one of those valid choices. Its syntax is as follows −

namespace AppBundle\Entity;  
use Symfony\Component\Validator\Constraints as Assert;  

class Student { 
   /** 
      * @Assert\Choice(choices = {"male", "female"}, message = "Choose a valid gender.") 
   */ 
   protected $gender; 
}

UserPassword

This validates that an input value is equal to the current authenticated user's password. This is useful in a form where users can change their password, but need to enter their old password for security. Its syntax is as follows −

namespace AppBundle\Form\Model; 
use Symfony\Component\Security\Core\Validator\Constraints as SecurityAssert; 

class ChangePassword { 
   /** 
      * @SecurityAssert\UserPassword( 
         * message = "Wrong value for your current password" 
      * ) 
   */ 
   protected $oldPassword;
} 

This constraint validates that the old password matches the user's current password.

Validation Example

Let us write a simple application example to understand the validation concept.

Step 1 − Create a validation application.

Create a Symfony application, validationsample, using the following command.

symfony new validationsample 

Step 2 − Create an entity named, FormValidation in file “FormValidation.php” under the “src/AppBundle/Entity/” directory. Add the following changes in the file.

FormValidation.php

<?php 
namespace AppBundle\Entity; 
use Symfony\Component\Validator\Constraints as Assert; 

class FormValidation {       
   /** 
      * @Assert\NotBlank() 
   */ 
   protected $name;  
      
   /** 
      * @Assert\NotBlank() 
   */ 
   protected $id;  
   protected $age;  
      
   /** 
      * @Assert\NotBlank() 
   */ 
   protected $address;  
   public $password;
      
   /** 
      * @Assert\Email( 
         * message = "The email '{{ value }}' is not a valid email.", 
         * checkMX = true 
      * ) 
   */ 
   protected $email;  
      
   public function getName() { 
      return $this->name; 
   }  
   public function setName($name) { 
      $this->name = $name; 
   }  
   public function getId() { 
      return $this->id; 
   } 
   public function setId($id) { 
      $this->id = $id; 
   }  
   public function getAge() { 
      return $this->age; 
   }  
   public function setAge($age) { 
      $this->age = $age;
   }  
   public function getAddress() { 
      return $this->address; 
   }  
   public function setAddress($address) { 
      $this->address = $address; 
   }  
   public function getEmail() { 
      return $this->email; 
   }  
   public function setEmail($email) { 
      $this->email = $email; 
   } 
}

Step 3 − Create a validateAction method in StudentController. Move to the directory “src/AppBundle/Controller”, create “studentController.php” file, and add the following code in it.

StudentController.php

use AppBundle\Entity\FormValidation; 
/** 
   * @Route("/student/validate") 
*/ 
public function validateAction(Request $request) { 
   $validate = new FormValidation(); 
   $form = $this->createFormBuilder($validate) 
      ->add('name', TextType::class)
      ->add('id', TextType::class) 
      ->add('age', TextType::class) 
      ->add('address', TextType::class) 
      ->add('email', TextType::class) 
      ->add('save', SubmitType::class, array('label' => 'Submit')) 
      ->getForm();  
      
   $form->handleRequest($request);  
   if ($form->isSubmitted() && $form->isValid()) { 
      $validate = $form->getData(); 
      return new Response('Form is validated.'); 
   }  
   return $this->render('student/validate.html.twig', array( 
      'form' => $form->createView(), 
   )); 
}   

Here, we have created the form using Form classes and then handled the form. If the form is submitted and is valid, a form validated message is shown. Otherwise, the default form is shown.

Step 4 − Create a view for the above created action in StudentController. Move to the directory “app/Resources/views/student/”. Create “validate.html.twig” file and add the following code in it.

{% extends 'base.html.twig' %} 
{% block stylesheets %} 
   <style> 
      #simpleform { 
         width:600px; 
         border:2px solid grey; 
         padding:14px; 
      }  
      #simpleform label {
         font-size:14px; 
         float:left; 
         width:300px; 
         text-align:right; 
         display:block; 
      }  
      #simpleform span { 
         font-size:11px; 
         color:grey; 
         width:100px; 
         text-align:right; 
         display:block; 
      }  
      #simpleform input { 
         border:1px solid grey; 
         font-family:verdana; 
         font-size:14px; 
         color:light blue; 
         height:24px; 
         width:250px; 
         margin: 0 0 10px 10px; 
      }  
      #simpleform textarea { 
         border:1px solid grey; 
         font-family:verdana; 
         font-size:14px; 
         color:light blue; 
         height:120px; 
         width:250px; 
         margin: 0 0 20px 10px;
      }  
      #simpleform select { 
         margin: 0 0 20px 10px; 
      }  
      #simpleform button { 
         clear:both; 
         margin-left:250px; 
         background: grey; 
         color:#FFFFFF; 
         border:solid 1px #666666; 
         font-size:16px; 
      } 
   </style> 
{% endblock %}  

{% block body %} 
   <h3>Student form validation:</h3> 
   <div id = "simpleform"> 
      {{ form_start(form) }} 
      {{ form_widget(form) }} 
      {{ form_end(form) }} 
   </div>   
{% endblock %}       

Here, we have used form tags to create the form.

Step 5 − Finally, run the application, http://localhost:8000/student/validate.

Result: Initial Page

Initial Page

Result: Final Page

Final Page

Advertisements
E-Books Store