function isValidUserName($username) { if(preg_match('/^[A-Za-z][A-Za-z0-9_-]{2,19}$/', $username)) { return true; } else { return false; } } $username = "john_doe123"; if(isValidUserName($username)) { echo "Valid username"; } else { echo "Invalid username"; }
use Illuminate\Validation\Rule; $data = [ 'username' => 'john_doe123', ]; $validator = Validator::make($data, [ 'username' => [ 'required', 'regex:/^[A-Za-z][A-Za-z0-9_-]{2,19}$/', Rule::unique('users','username')->ignore($user->id) ] ]); if ($validator->fails()) { return redirect()->back()->withErrors($validator); }In this example, the Laravel validation library is used to validate a username. The `required` rule ensures that the `username` field is not empty. The `regex` rule checks if the username matches the required format. The `unique` rule ensures that the username is not already taken by another user. If any validation fails, an error message is returned. Package Library: That's no package library. It is just built-in "regular expression" function in PHP.