How does Laravel Validate String?

Viewed 3375

When I use Laravel's string validation rule, what exactly is it doing? For example, does it simply run php's is_string() method, or does it run filter_var() perhaps, with the FILTER_VALIDATE_REGEXP constant?

Secondly, how do I strip tags using Laravel?

3 Answers

When you use Laravel's string validation, the following function gets called

protected function validateAttribute($attribute, $rule) { ... }

which you could find in

vendor/laravel/framework/src/Illuminate/Validation/Validator.php

and if you examine the method, you'll find this piece of code

$method = "validate{$rule}";

if ($validatable && ! $this->$method($attribute, $value, $parameters, $this)) {
    $this->addFailure($attribute, $rule, $parameters);
}

which would call the trait Concerns\ValidatesAttributes

/**
 * Validate that an attribute is a string.
 *
 * @param  string  $attribute
 * @param  mixed   $value
 * @return bool
 */
public function validateString($attribute, $value)
{
    return is_string($value);
}

and to strip tags you could use PHP's strip_tags method

You can try this

This are some validations i used in my current project,it is based on user input.

$username = $request->get('username');
$email = $request->get('email');
$password = $request->get('password');
if (!preg_match("/^[a-zA-Z0-9]*$/", $username)) {
      return abort(403, 'Username should be alphanumeric');
   }
if(strlen($username) < 3 || strlen($username) > 25){
      return abort(403, 'Username should mbe minimum 3 and max 25 characters');
   }
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
      return abort(403, 'Invalid Email Format,eg abc@xyz.com');
   }
if(strlen($password) < 6){
      return abort(403, 'Password should be minimum six characters');
   }

refer https://laravel.com/docs/5.7/validation.

To strip tags in laravel you can use strip_tags() function in your code .The strip_tags() function strips a string from HTML, XML, and PHP tags. HTML comments are always stripped. This cannot be changed with the allow parameter. This function is binary-safe.

Related