Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

kerelka's avatar

Do I need to add RegEx validation to avoid script injection or any kind of form manipulation attacks?

I have a concern, let's say I have an input called 'name'

public function index(Request $request) {
	$request->validate([
		'name' => ['required', 'string', 'max:255'],
    ]);
}

to avoid any kind of script or tag injection. do i need to add additional regex validation and tag stripping? or is it not necessary at all as long as i use ORM

0 likes
5 replies
LaryAI's avatar
Level 58

You generally do not need to add additional RegEx validation or tag stripping at the validation stage just to prevent script or tag injection, especially if you’re using Laravel’s ORM (Eloquent) and Blade templating engine.

Here’s why:

  • Validation (like 'string', 'max:255') ensures the data is the correct type and length, but does not sanitize it.
  • ORM/Eloquent protects against SQL injection by parameterizing queries.
  • Blade templates automatically escape output with {{ $name }} to prevent XSS (Cross-Site Scripting).

You only need to worry about XSS if you output user data without escaping, for example using {!! $name !!} or in JavaScript contexts.

If you want to restrict certain characters (like HTML tags) for business logic reasons, you can add a regex:

'name' => ['required', 'string', 'max:255', 'regex:/^[a-zA-Z\s]+$/']

But for security, escaping output is the key. You do not need to strip tags or use regex just for security if you follow Laravel’s conventions.

Summary:

  • Use 'string' and 'max:255' for validation.
  • Use {{ $name }} in Blade to escape output.
  • Only add regex/tag stripping if your business logic requires it, not for security.

References:

Glukinho's avatar

Don't worry about it, it is already covered by Laravel & Eloquent.

Of course there may be complex situations where you need to be extra cautious. For example, when a user sends you HTML markup or potentially dangerous files and you intend to process it somehow.

2 likes
JussiMannisto's avatar

The ORM uses prepared statements, so SQL injections are not a concern. What you do with the data elsewhere is a different topic. If you ever inject those values in your HTML, you need to escape them. How that's done depends on the UI technology you're using. For example:

// In Blade, you escape values with double curly braces:
<input type="text" name="name" value="{{ old('name') }}" />

// React escapes values automatically:
<input type="text" name="name" value={data.name} />

Don't mess around with strip_tags, just escape the whole string. Unless you explicitly need to allow some (unescaped) HTML tags.

2 likes

Please or to participate in this conversation.