-1

I want to check if username contains both letters and numbers.I was trying to use alpha_num

protected function validator(array $data)
{
    return Validator::make($data, [
    'name' => 'required',   
    'username' => 'required|alpha_num',
    'password' => 'min:6|required',
    ]);
}

But it didn't work. Kindly help me solve this problem.

Mahbub
  • 11
  • 1
  • 8
  • Do you need the username to follow a certain pattern? Or just check if it contains letters and numbers? – Robert Jan 10 '17 at 16:38
  • I want just check if it contains at least one letter & one number.Like John123,Not john or 123. – Mahbub Jan 10 '17 at 17:22
  • Combine the custom validation referred to by Crozet with the regex in this answer: http://stackoverflow.com/a/7684859/1483117 – Robert Jan 10 '17 at 17:25
  • What does "didn't work" mean? What is it doing that constitutes a non-working state? – maiorano84 Jan 10 '17 at 19:50

2 Answers2

0

The alpha_num filter just checks if the username contains only letters and numbers but not if both are present.

Depending on your need, there are two regex that can validate the username

If you want (at least) one letter and one number and whatever else

if (preg_match('/[A-Za-z]/', $myString) && preg_match('/[0-9]/', $myString))
{
    echo 'Contains at least one letter and one number';
}
  • 1a]-/*+ and aaaaaaaa1 will pass this test
  • 1-_% and a will not pass the test

If you want (at least) one letter and one number but only letters and numbers

if (preg_match('/^(?=.*[0-9])(?=.*[a-zA-Z])([a-zA-Z0-9]+)$/', $myString))
{
    echo 'Contains at least one letter and one number and only alphanum';
}

more info about this regex : https://regex101.com/r/GrLGbT/1

  • 1111111a and aaaaaaaa1 will pass this test
  • 1a- and a will not pass the test

Once you have your regex, you will need to create a custom validator. Have a look here for the doc : https://laravel.com/docs/5.3/validation#custom-validation-rules

ᴄʀᴏᴢᴇᴛ
  • 2,939
  • 26
  • 44
0

if you want input not to be numeric you can try 'name' => 'required|regex:/^[\pL\s-]+$/u|max:255',

if you want it to be alpha numeric then: 'name' => 'required|string|max:255',

Fareesa
  • 81
  • 1
  • 3