양식 제출에서 데이터 유효성 검사를 효과적으로 처리하는 방법은 무엇입니까?효과적인 데이터 유효성 검사
원래 각 값을 검사하고 나중에 검색 (및 나열)을 위해 배열에 잘못된 값을 수집 한 if
문장이있었습니다.
// Store errors here
$errors = array();
// Hypothetical check if a string is alphanumeric
if (!preg_match('/^[a-z\d]+$/i', $fieldvalue))
{
$errors[$fieldname] = 'Please only use letters and numbers for your street address';
}
// etc...
내가 다음에 수행 한 작업은 다양한 데이터 유효성 검증 시나리오를 처리하고 결과를 내부 배열에 저장하는 클래스를 만드는 것입니다. 데이터 유효성 검사를 완료 한 후 나는 어떤 오류가 발생했는지 확인하고 그에 따라 처리 할 것 :
class Validation
{
private $errorList = array();
public function isAlphaNumeric($string, $field, $msg = '')
{
if (!preg_match('/^[a-z\d]+$/i', $string))
{
$this->errorList[$field] = $msg;
}
}
// more methods here
public function creditCard($cardNumber, $field, $msg = '')
{
// Validate credit card number
}
// more methods here
public function hasErrors()
{
return count($this->errorList);
}
}
/* Client code */
$validate = new Validation();
$validate->isAlphaNumeric($fieldvalue1, $fieldname1, 'Please only use letters and numbers for your street address');
$validate->creditCard($fieldvalue2, $fieldname2, 'Please enter a valid credit card number');
if ($validate->hasErrors())
{
// Handle as appropriate
}
는 당연히이 클래스의 유효성을 검사 할 데이터의 무제한 종류 부풀어되었다 오래 전에하지 않았다. 내가 지금하고 있어요 자신의 클래스로 데이터의 다른 유형을 분리하고 일반적인 검증을 떠나 필요한 경우에만 그들을 호출하는 장식을 사용 (예 : isAlphaNumeric()) 기본 클래스 :
class Validation
{
private $errorList = array();
public function isAlphaNumeric($string, $field, $msg = '')
{
if (!preg_match('/^[a-z\d]+$/i', $string))
{
$this->errorList[$field] = $msg;
}
}
// more generic methods here
public function setError($field, $msg = '')
{
$this->errorList[$field] = $msg;
}
public function hasErrors()
{
return count($this->errorList);
}
}
class ValidationCreditCard
{
protected $validate;
public function __construct(Validation $validate)
{
$this->validate = $validate;
}
public function creditCard($cardNumber, $field, $msg = '')
{
// Do validation
// ...
// if there is an error
$this->validate->setError($field, $msg);
}
// more methods here
}
/* Client code */
$validate = new Validation();
$validate->isAlphaNumeric($fieldvalue, $fieldname, 'Please only use letters and numbers for your street address');
$validateCC = new ValidationCreditCard($validate);
$validateCC->creditCard($fieldvalue2, $fieldname2, 'Please enter a valid credit card number');
if ($validate->hasErrors())
{
// Handle as appropriate
}
내가 오전 바른 길? 아니면 필자는 필자가 필요로하는 것 이상으로 데이터 검증을 복잡하게 만들었습니까?
:
도에서 참조하시기 바랍니다. 나는 또한이 Ques의 대답을 얻는 것에 흥미가있을 것이다. Currenlty는 또한 양식을 확인합니다. 내가 가능한 TryParse 및 다른 inbuild 함수를 사용합니다. 남은 것은 나 자신을 만든다. –