- Symfony 教程
- Symfony - 首頁
- Symfony - 簡介
- Symfony - 安裝
- Symfony - 架構
- Symfony - 元件
- Symfony - 服務容器
- Symfony - 事件 & 事件監聽器
- Symfony - 表示式
- Symfony - Bundles
- 建立簡單的 Web 應用程式
- Symfony - 控制器
- Symfony - 路由
- Symfony - 檢視引擎
- Symfony - Doctrine ORM
- Symfony - 表單
- Symfony - 驗證
- Symfony - 檔案上傳
- Symfony - Ajax 控制
- Cookie & 會話管理
- Symfony - 國際化
- Symfony - 日誌記錄
- Symfony - 郵件管理
- Symfony - 單元測試
- Symfony - 高階概念
- Symfony - REST 版本
- Symfony - CMF 版本
- 完整的執行示例
- Symfony 有用資源
- Symfony - 快速指南
- Symfony - 有用資源
- Symfony - 討論
Symfony - 驗證
在設計應用程式時,驗證是最重要的方面。它會驗證傳入的資料。本章詳細解釋了表單驗證。
驗證約束
驗證器旨在根據約束驗證物件。如果驗證物件,只需將一個或多個約束對映到其類,然後將其傳遞給驗證器服務。預設情況下,在驗證物件時,將檢查相應類所有約束以檢視它們是否真正透過。Symfony 支援以下值得注意的驗證約束。
NotBlank
驗證屬性不為空白。其語法如下:
namespace AppBundle\Entity;
use Symfony\Component\Validator\Constraints as Assert;
class Student {
/**
* @Assert\NotBlank()
*/
protected $studentName;
}
此 NotBlank 約束確保 studentName 屬性不為空白。
NotNull
驗證值不嚴格等於 null。其語法如下:
namespace AppBundle\Entity;
use Symfony\Component\Validator\Constraints as Assert;
class Student {
/**
* @Assert\NotNull()
*/
protected $studentName;
}
驗證值是否為有效的電子郵件地址。其語法如下:
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
驗證值是否完全等於 null。其語法如下:
namespace AppBundle\Entity;
use Symfony\Component\Validator\Constraints as Assert;
class Student {
/**
* @Assert\IsNull()
*/
protected $studentName;
}
Length
驗證給定字串的長度是否在某個最小值和最大值之間。其語法如下:
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
驗證給定數字是否在某個最小值和最大值之間。其語法如下:
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
驗證值是否為有效日期。它遵循有效的 YYYY-MM-DD 格式。其語法如下:
namespace AppBundle\Entity;
use Symfony\Component\Validator\Constraints as Assert;
class Student {
/**
* @Assert\Date()
*/
protected $joinedAt;
}
Choice
此約束用於確保給定值是給定一組有效選項中的一個。它還可以用於驗證專案陣列中的每個專案是否為這些有效選項之一。其語法如下:
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
這會驗證輸入值是否等於當前已認證使用者的密碼。這在使用者可以更改其密碼但出於安全原因需要輸入其舊密碼的表單中很有用。其語法如下:
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;
}
此約束驗證舊密碼是否與使用者的當前密碼匹配。
驗證示例
讓我們編寫一個簡單的應用程式示例來理解驗證的概念。
步驟 1 - 建立驗證應用程式。
使用以下命令建立 Symfony 應用程式 validationsample。
symfony new validationsample
步驟 2 - 在 “src/AppBundle/Entity/” 目錄下的 “FormValidation.php” 檔案中建立名為 FormValidation 的實體。在檔案中新增以下更改。
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;
}
}
步驟 3 - 在 StudentController 中建立 validateAction 方法。移動到 “src/AppBundle/Controller” 目錄,建立 “studentController.php” 檔案,並在其中新增以下程式碼。
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(),
));
}
在這裡,我們使用 Form 類建立了表單,然後處理了表單。如果表單提交且有效,則顯示錶單驗證訊息。否則,將顯示預設表單。
步驟 4 - 為 StudentController 中建立的操作建立檢視。移動到 “app/Resources/views/student/” 目錄。建立 “validate.html.twig” 檔案並在其中新增以下程式碼。
{% 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 %}
在這裡,我們使用了表單標籤來建立表單。
步驟 5 - 最後,執行應用程式,https://:8000/student/validate。
結果:初始頁面
結果:最終頁面