XSS Payload Pattern (Basic Detection) Regex for Python
/(?:<script[\s>]|<\/script>|javascript:|vbscript:|onload\s*=|onerror\s*=|onclick\s*=|onmouseover\s*=|<iframe\b|<object\b|<embed\b|<svg[\s>]|document\.cookie|document\.write|eval\s*\(|setTimeout\s*\(|setInterval\s*\(|window\.location|alert\s*\(|confirm\s*\(|prompt\s*\(|data:text/html)/iWhat this pattern does
This page provides a comprehensive, battle-tested regular expression for matching xss payload pattern (basic detection), ported and verified for Python. In security-sensitive code, using an unverified regex can open the door to both false positives and denial-of-service attacks. The snippet below is ready to drop into your Python project — whether you're validating in a Django view, a FastAPI endpoint, or a standalone data processing script.
Python Implementation
# XSS Payload Pattern (Basic Detection)
# ReDoS-safe | RegexVault — Security > Injection Patterns
import re
xss_payload_pattern_basic_detection_pattern = re.compile(r'(?:<script[\s>]|<\/script>|javascript:|vbscript:|onload\s*=|onerror\s*=|onclick\s*=|onmouseover\s*=|<iframe\b|<object\b|<embed\b|<svg[\s>]|document\.cookie|document\.write|eval\s*\(|setTimeout\s*\(|setInterval\s*\(|window\.location|alert\s*\(|confirm\s*\(|prompt\s*\(|data:text/html)')
def validate_xss_payload_pattern_basic_detection(value: str) -> bool:
return bool(xss_payload_pattern_basic_detection_pattern.fullmatch(value))
# Example
print(validate_xss_payload_pattern_basic_detection("<script>alert(1)</script>")) # TrueTest Cases
Matches (Valid) | Rejects (Invalid) |
|---|---|
<script>alert(1)</script> | Hello World |
javascript:void(0) | This is a normal comment |
onload=malicious() | <b>Bold text</b> |
<svg onload=alert(1)> | onclick is a word |
document.cookie | — |
When to use this pattern
This pattern is drawn from the Security > Injection Patterns category and carries a ReDoS-safe certification. That matters for Python developers because particularly important in Python web servers where CPU-bound regex operations can stall concurrent request handling. RegexVault audits patterns against known backtracking attack vectors, ensuring you have the necessary context before using this regex in a high-stakes production environment.
Common Pitfalls
There are over 1000 known XSS filter bypass techniques. Regex-based XSS filtering in input validation is cat-and-mouse. Use DOMPurify for sanitizing user HTML, and rely on CSP (Content Security Policy) as the final layer of defense.
Technical Notes
Basic XSS detection. Incomplete — XSS payloads can be encoded in dozens of ways (HTML entities, Unicode escapes, UTF-7, etc.). Use as a signal for logging/alerting. The real defense is output encoding via a template engine (React, Vue, Jinja2 with auto-escaping).
Have a pattern that belongs in the vault?
Submit it for review — community-verified patterns get credited to your GitHub handle. Free submissions join the queue. Priority review available for $15.
Submit a Pattern