简体   繁体   中英

How does Laravel Validate String?

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?

When I use Laravel's string validation rule, what exactly is it doing?

When you use Laravel's string validation rule, it only checks if the field under validation is of string type or not .

https://laravel.com/docs/5.0/validation#rule-string

how do I strip tags using Laravel?

You can use the strip_tags() function:

http://php.net/manual/en/function.strip-tags.php

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM