在PHP中批量校验字段的有效性

在批量校验字段的有效性时,有很多校验规则是可以重复利用的,这样我们可以定义一个校验类将所有校验规则都收敛到这个类中,并对外提供一个可调用的校验方法。

定义校验类

class Validator {
    // 长度校验
    const MIN_LEN = "minLen";

    // 取值范围校验
    const RANGE = "range";
    const POSITIVE = "positive";
    const NEGATIVE = "negative";
    const NOT_POSITIVE = "notPositive";
    const NOT_NEGATIVE = "notNegative";

    // 数据类型校验
    const NUMERIC = "numeric";
    const INT = "int";


    static protected $_typeMap = [
        self::RANGE => 'self::isInRange',
        self::MIN_LEN => 'self::checkMinLen',
        self::INT => 'self::isInt',
        self::POSITIVE => 'self::isPositive',
        self::NEGATIVE => 'self::isNegative',
        self::NOT_POSITIVE => 'self::isNotPositive',
        self::NOT_NEGATIVE => 'self::isNotNegative',
        self::NUMERIC => 'self::isNumeric',
    ];

    public static function check($type, $v, $rule) {
        return call_user_func_array(self::$_typeMap[$type], [$v, $rule]);
    }

    private static function isNumeric($v, $cond) {
        return is_numeric($v);
    }

    private static function isInRange($v, $range) {
        if (!is_array($range) || count($range) != 2) {
            return false;
        }

        return $v >= $range[0] && $v <= $range[1];
    }

    private static function checkMinLen($v, $len) {
        return strlen($v) >= $len;
    }

    private static function isInt($v, $cond) {
        if (is_int($v)) {
            return true;
        }

        $i = intval($v);

        return "{$i}" == $v;
    }

    private static function isPositive($v, $cond) {
        return is_numeric($v) && intval($v) > 0;
    }

    private static function isNegative($v, $cond) {
        return is_numeric($v) && intval($v) < 0;
    }

    private static function isNotPositive($v, $cond) {
        return is_numeric($v) && intval($v) <= 0;
    }

    private static function isNotNegative($v, $cond) {
        return is_numeric($v) && intval($v) >= 0;

    }
}

定义校验方法

function checkFields($rules, $data) {
    foreach ($rules as $field => $fieldRules) {
        if (!isset($data[$field])) {
            echo "missing param $field \n";
            return false;
        }
    }

    foreach ($rules as $field => $fieldRules) {
        foreach ($fieldRules as $type => $rule) {
            $ret = Validator::check($type, $data[$field], $rule);
            if ($ret == false) {
                echo "param $field is invalid!\n";
                return false;
            }
        }
    }

    return true;
}

使用示例

  • 定义多个字段的校验规则
$checkRules = array(
    '/a/b' => [
        'name' => [
            Validator::MIN_LEN => 1,
        ],
        'age' => [
            Validator::NOT_NEGATIVE => true,
        ],
    ],
    '/a/c' => [
        'orderId' => [
            Validator::MIN_LEN => 1,
        ],
        'timestamp' => [
            Validator::NOT_NEGATIVE => true,
        ],
    ],
    '/a/d' => [
        'uid' => [
            Validator::MIN_LEN => 1,
        ],
        'pageNo' => [
            Validator::NOT_NEGATIVE => true,
        ],
        'pageSize' => [
            Validator::RANGE => [1, 1000],
        ],
    ],
);
  • 调用校验方法对字段进行批量校验
class TestController
{
    function AB()
    {
        global $checkRules;
        $params = array(
            'name' => 'zhoumin',
            'age' => 0,
        );
        $ret = checkFields($checkRules['/a/b'], $params);
        if ($ret == false) {
            echo "params are invalid!\n";
            return;
        } else {
            echo "params are valid!\n";
        }
    }

    function AC()
    {
        global $checkRules;
        $params = array(
            'orderId' => '330159',
            'timestamp' => 1601234567, // 2020/9/28 3:22:47
        );
        $ret = checkFields($checkRules['/a/c'], $params);
        if ($ret == false) {
            echo "params are invalid!\n";
            return;
        } else {
            echo "params are valid!\n";
        }
    }

    function AD()
    {
        global $checkRules;
        $params = array(
            'uid' => 8888,
            'pageNo' => 3,
            'pageSize' => -20,
        );
        $ret = checkFields($checkRules['/a/d'], $params);
        if ($ret == false) {
            echo "params are invalid!\n";
            return;
        } else {
            echo "params are valid!\n";
        }
    }
}

$tc = new TestController();
$tc->AB();
$tc->AC();
$tc->AD();
  • 执行结果
params are valid!
params are valid!
param pageSize is invalid!
params are invalid!

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在将 Excel 数据导入到 MySQL 数据库时,你可以使用参数校验来确保导入的字段满足要求。下面是一个示例代码,展示了如何进行参数校验: ```go import ( "errors" "fmt" "strconv" ) // 检查字段是否为空 func validateFieldNotEmpty(field string) error { if field == "" { return errors.New("字段不能为空") } return nil } // 检查字段是否为有效的整数 func validateFieldIsInteger(field string) error { _, err := strconv.Atoi(field) if err != nil { return fmt.Errorf("字段不是有效的整数: %s", field) } return nil } // 示例代码:从 Excel 导入数据到 MySQL func importExcelDataToMySQL(data [][]string) error { for _, row := range data { if err := validateFieldNotEmpty(row[0]); err != nil { return err } if err := validateFieldIsInteger(row[1]); err != nil { return err } // 在这里执行插入数据库的操作 // ... } return nil } func main() { // 假设从 Excel 读取到的数据是一个二维字符串数组 excelData := [][]string{ {"John Doe", "25"}, {"Jane Smith", "30"}, {"", "abc"}, } err := importExcelDataToMySQL(excelData) if err != nil { fmt.Println("导入数据发生错误:", err) } } ``` 在上述示例,我们定义了两个参数校验函数:`validateFieldNotEmpty` 用于检查字段是否为空,`validateFieldIsInteger` 用于检查字段是否为有效的整数。在 `importExcelDataToMySQL` 函数,我们根据需要调用这些校验函数来验证每个字段的合法性。如果校验失败,将返回相应的错误信息。 你可以根据实际需求扩展和改进这些参数校验函数,以满足你的具体要求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值