使用php函数验证字段的更好方法


Better way to validate fields using function php

为了验证给定字段,我编写了这样的函数。请审查和改进我的功能,以项目有价值的

我的领域

try{
    $message = 'First Name accepts keyboard characters only.';
    doValidateField ( $firstName, 'First Name', true, 100, '/^([a-zA-Z0-9._'- #,^&`~<>:!@$(){}'"'';'*'[']?%| 'n 'r 't]*)$/', $message );
} catch ( Exception $e ) {
    $errorMessage = $e->getMessage ();
    echo $errorMessage;
}

功能

/*
* The following function is validates the fields
* @params unknown values $fieldValue, $fieldName, $required, $maxLength, $mask, $message
* @return tables rows $rowResponse
*/
function doValidateField($fieldValue, $fieldName, $required, $maxLength, $mask, $message) {
    // Checking the required field is empty or not
    if ($required) {
        if (strlen ( $fieldValue ) <= 0) {
            throw new Exception ( $fieldName . " is required." );
        }
    }
    // Check field length is not greater than allowed length
    if (strlen ( $fieldValue ) > $maxLength) {
        throw new Exception ( $fieldName . " cannot be greater than " . $maxLength . " characters." );
    }
    // check if specified mask exists in the field
    if (! (preg_match ( $mask, $fieldValue ))) {
        throw new Exception ( $message );
    }
}

这可能没有你想要的答案那么具体,但我建议你看看Zend_Validator类使用的一些模式和想法。(上面写着"Zend",但它不是PHP的默认部分。)

关于这一点:

  • 我不会抛出例外。它可以更容易地找到第一个问题,但更难通过多个验证器循环。通常,你会想向所有的人展示他们犯错误的地方,而不是只显示第一个问题,让他们反复提交表格来解决所有问题
  • 不要创建验证函数,创建一个验证类。基本上,使用OOP。它不仅使代码更干净、更容易改进,而且您还可以复制验证器,并根据需要稍微调整它们的规则/消息
  • 记住,当你开始处理带有重音的字符或不同的语言时,事情会变得有点奇怪。弄清楚你正在构建的东西是否需要额外的工作