IP地址的Cakephp验证规则

时间:2016-12-20 09:55:11

标签: validation cakephp cakephp-3.0

我正在尝试为Ip-Address创建验证规则,以下代码无效:

$validator
        ->add('ipfirst', 'validIp', ['rule' => 'ip', 'message' => 'Ip is not valid!'])
        ->requirePresence('ipfirst', 'create')
        ->notEmpty('ipfirst');

如果有人能直接指出我,那就太棒了,谢谢!

2 个答案:

答案 0 :(得分:2)

Cake 3.x中已有IPv4和IPv6验证方法: - )

http://api.cakephp.org/3.3/class-Cake.Validation.Validator.html#_ipv4& http://api.cakephp.org/3.3/class-Cake.Validation.Validator.html#_ipv6

像这样使用它:

$validator
    ->ipv4('ipfirst', 'Please enter ip address')
    ->requirePresence('ipfirst', 'create')
    ->notEmpty('ipfirst');

当然,如果你想要的话,改为ipv6:P

答案 1 :(得分:-2)

You can add custom validation rule with regular expression like:
// you can change regular expression according to you requirement.
$validator
    ->notEmpty('ipfirst', 'Please enter ip address')
    ->add('ipfirst','validIp',[
        'rule'=>  function($value){
            if (preg_match('/^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/', $value)) {
                    return true;
            }
            return false;
        },
        'message'=>'Please enter a valid ip address.',
    ]);