search

Home  >  Q&A  >  body text

How to write username validation rules in Laravel?

The requirement is that it must contain letters and numbers.

For example, pure numbers are not allowed.

How to implement it using laravel's own verification method?

天蓬老师天蓬老师2782 days ago706

reply all(6)I'll reply

  • 巴扎黑

    巴扎黑2017-05-16 16:53:23

    Just use this regular rule, it has been tested, [a-zA-Z]+([A-Za-z0-9])*

    Achieve the effect, such as when registering a username:

    55555 failed
    8754xcc failed
    hhgdG55 passed
    hhgdG55? failed
    ggh hhd failed
    with Chinese failed

    It seems that you can only use regular expressions, laravel does not provide corresponding function support (functions in the shape of alpha_num)

    reply
    0
  • 習慣沉默

    習慣沉默2017-05-16 16:53:23

    //获取表单的值
    $username = $request->input('username');
    $password = $request->input('password');
    
    //登录表单验证
    $validator = Validator::make($request->all(), [
      'username' => 'required|alpha_num|regex:/^(?!([A-Za-z]+|d\d+)$)[A-Za-z\d]$/',  //只允许数字和字母
    ]);
    
    //表单验证失败提示
    if ($validator->fails()) {
      //此处省略。。。
    }

    Not tested.

    reply
    0
  • 某草草

    某草草2017-05-16 16:53:23

    You probably haven’t seen the Validation part of the Laravel5 document yet~ You can write a Request to verify the username

    reply
    0
  • ringa_lee

    ringa_lee2017-05-16 16:53:23

     $form_data = [
                "product_name" => $request->get('product_name'),      
            ];
    $rules = [
                "product_name" => 'required'
            ];
    $messages = [
                'required' => ' :attribute 字段必须填写.',
            ];        
    $validate = Validator::make($form_data, $rules,$messages);
    if ($validate ->fails()){
        return redirect('admin/addProduct')->withErrors($validate)->withInput();
            }

    I don’t know if I can help you

    reply
    0
  • 仅有的幸福

    仅有的幸福2017-05-16 16:53:23

    You need a laravel document: Baidu Cloud. After downloading the document, please check [Directory] [Service] [Service - Verification], or [Search] "Validator".

    reply
    0
  • ringa_lee

    ringa_lee2017-05-16 16:53:23

    Verification rules can be customized

    reply
    0
  • Cancelreply