[英]Validate JSON Request with Respect/Validation
我有一個 JSON 請求,完全符合規則,但結果一直失敗。 假設我有這樣的請求:
{
"name" : "Angela White",
"dateOfBirth" : "01/01/98"
}
這是我的 controller:
class RegisterController extends Controller {
public function register($request, $response) {
$parsedBody = $request->getParsedBody();
$name = trim($parsedBody['name']);
$dateOfBirth = $parsedBody['dateOfBirth'];
$customer = new Customer();
$customer->setName($name);
$customer->setDateOfBirth($dateOfBirth);
$rules = $customer->customerValidator();
$data = array(
'name' => $name,
'dateOfBirth' => $dateOfBirth,
);
foreach($data as $key => $val) {
try{
$rules->check($val);
} catch(\InvalidArgumentException $e) {
$errors = $e->getMessage();
return $response->withJson($errors, 401);
}
}
}
}
這是 class 來驗證數據:
class Customer {
private $name;
private $dateOfBirth;
public function setName($input) {
$this->name = $input;
}
public function getName() {
return $this->name;
}
public function setDateOfBirth($input) {
$this->dateOfBirth = $input;
}
public function getDateOfBirth() {
return $this->dateOfBirth;
}
public function customerValidator() {
return v::attribute($this->getName(), v::stringType()->length(2, null)->setName('Name'))
->attribute('dateOfBirth', v::notEmpty()->date('d/m/y')->setName('Date of birth'));
}
}
結果我得到了這個:
{
"API_Response": {
"Status": {
"Message": "Attribute Name must be present",
"_ErrorCode": 401,
"_TimeStamp": 1647247097
}
}
}
我希望結果是成功的,但為什么消息仍然是“屬性名稱必須存在”? 有誰能幫助我,我錯過了什么? 謝謝!
有不同的問題。
位於customerValidator
function 中的那個。在這里,您使用的是接受屬性名稱而不是其值的屬性規則。 將$this->getName()
替換為'name'
應該就足夠了:
class Customer {
private $name;
private $dateOfBirth;
public function setName($input) {
$this->name = $input;
}
public function getName() {
return $this->name;
}
public function setDateOfBirth($input) {
$this->dateOfBirth = $input;
}
public function getDateOfBirth() {
return $this->dateOfBirth;
}
public function customerValidator() {
return v::attribute('name', v::stringType()->length(2, null)->setName('Name'))
->attribute('dateOfBirth', v::notEmpty()->date('d/m/y')->setName('Date of birth'));
}
}
您已經擁有設置了所有屬性的 object,因此最好對其進行驗證,而不是遍歷您定義的所有鍵。
class RegisterController extends Controller {
public function register($request, $response) {
$parsedBody = $request->getParsedBody();
$name = trim($parsedBody['name']);
$dateOfBirth = $parsedBody['dateOfBirth'];
$customer = new Customer();
$customer->setName($name);
$customer->setDateOfBirth($dateOfBirth);
$rules = $customer->customerValidator();
$data = array(
'name' => $name,
'dateOfBirth' => $dateOfBirth,
);
try{
$rules->check($customer);
} catch(\InvalidArgumentException $e) {
$errors = $e->getMessage();
return $response->withJson($errors, 401);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.