Laravel 4正则表达式:密码无效的模式验证

时间:2015-01-28 10:36:12

标签: regex validation laravel-4

我试图使用正则表达式验证Laravel 4中的密码强度。我是按照以下方式尝试的,但它始终是在给我“密码弱”'作为回报,如果我的$验证器验证通过。

public function checkPassStrength(){
    $password = Input::get('password');
    $validator = Validator::make(Input::all(), array(
        'password' => 'alpha_dash|min:6'
    ));
    $niceNames = array(
        'password' => 'Password'
    );
    $validator->setAttributeNames($niceNames);
    if($validator->fails()) {
        return Response::json(array('valid' => false, 'msg' => $validator->messages()->first('password')));
    } else {
        $strong = Validator::make(Input::all(), array(
            'password' => array('regex:/^(?=.*[A-Z])(?=.*[!@#$&*])(?=.*[0-9])(?=.*[a-z])$/')
        ));
        $medium = Validator::make(Input::all(), array(
            'password' => array('regex:/^(?=.*[A-Z])(?=.*[0-9])(?=.*[a-z])$/')
        ));
        if($strong->passes()){
            return Response::json(array('valid' => false, 'msg' => 'Password is strong'));
        } elseif($medium->passes()){
            return Response::json(array('valid' => false, 'msg' => 'Password is medium'));
        } else {
            return Response::json(array('valid' => false, 'msg' => 'Password is weak'));
        }

    }
}

1 个答案:

答案 0 :(得分:1)

Lookahead是一个zolelength断言,在正则表达式的末尾添加.+

/^(?=.*[A-Z])(?=.*[!@#$&*])(?=.*[0-9])(?=.*[a-z]).+$/

或者,如果要将长度限制为8到20个字符:

/^(?=.*[A-Z])(?=.*[!@#$&*])(?=.*[0-9])(?=.*[a-z]).{8,20}$/