Replace regex with Jinja2

3 weeks ago 16
ARTICLE AD BOX

You can use the following syntax:

<input mixvalidate="^.{ {{-USER_USERNAME_MIN}},{{USER_USERNAME_MAX}}}$">

The {{ }} wrappers are the standard way to inject jinja variables. Here a space is used to distinguish the literal opening brace from such injection-syntax, and the minus sign is used to remove that white space in the final result.

See it on packetcoders.io/j2-render

trincot's user avatar

If you want to assert that the username is between 2 and 20 characters, then use this regular expression:

^.{2,20}$

Updated code:

<input mixvalidate="^.{2,20}$">

Tim Biegeleisen's user avatar

1 Comment

Sure. Though I want to place the constants into the regex

2026-02-25T14:41:51.357Z+00:00

You can make it dynamic with Jinja2 so you don’t have to change the regex in multiple places. For your case:

<input mixvalidate="^.{ {{ USER_USERNAME_MIN }},{{ USER_USERNAME_MAX }} }$">

{{ USER_USERNAME_MIN }} and {{ USER_USERNAME_MAX }} will be replaced with the values from app.py.

Make sure you pass those variables to your template:

from flask import render_template # or FastAPI/Jinja2 equivalent return render_template("template.html", USER_USERNAME_MIN=USER_USERNAME_MIN, USER_USERNAME_MAX=USER_USERNAME_MAX)

✅ Now if you change USER_USERNAME_MIN or USER_USERNAME_MAX in your Python file, the input validation updates automatically.

Mohaned Hassan's user avatar

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.

Read Entire Article