Open igorsimb opened 1 year ago
This could be a good way to validate such form (forms.py):
class SkuFormatValidator(BaseValidator):
"""
Custom validator that checks if the provided SKUs are in the correct format.
It ensures that SKUs are separated by comma, space, or newline and do not contain any letters
"""
message = _(
"Invalid SKU format. SKUs should be separated by comma, space, or newline and should not contain letters.")
code = "Invalid SKU format"
def __init__(self):
super().__init__(self.message, self.code)
def __call__(self, value):
# Split the value by comma, space, or newline and check if each part is a valid SKU
skus = value.split(',')
skus = [sku.strip() for s in skus for sku in s.split() if sku.strip()]
for sku in skus:
if not re.match(r'^[0-9]+$', sku):
logger.warning("Invalid SKU: %s", sku)
raise ValidationError(self.message, code=self.code, params={"value": value})
else:
logger.info("Valid SKU: %s", sku)
Then call for the validators
in the form
class ScrapeForm(forms.Form):
skus = forms.CharField(
label="SKUs",
widget=forms.Textarea,
help_text="Введите один или несколько артикулов через запятую, пробел или с новой строки.",
validators=[SkuFormatValidator()],
)
In the template.html:
{% if form.errors %}
{% for field in form %}
{% for error in field.errors %}
<div class="alert alert-danger">
<strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endfor %}
{% endif %}
or (less elegant)
{% if form.errors %}
<!-- Error messaging -->
<div id="errors">
<div class="inner">
<p>There were some errors in the information you entered. Please correct the following:</p>
<ul>
{% for field in form %}
{% if field.errors %}<li>{{ field.label }}: {{ field.errors|striptags }}</li>{% endif %}
{% endfor %}
</ul>
</div>
</div>
<!-- /Error messaging -->
{% endif %}
The conditions:
e.g. 141540568, 13742696,20904017 3048451