In AnQiCMS content operation practice, we often need to handle various data submitted by users, which may not be simple text or numbers, but structured information containing multiple elements, such as tags of an article, multiple features of a product page, or multiple choices in a questionnaire.Validating this input effectively, ensuring it meets our expected quantity requirements, is a key step in improving data quality and user experience.

AnQiCMS template engine provides a very practicalsplitfilter that can help us easily validate structured user input data at the template level.

KnowsplitFilter

In AnQiCMS templates,splitFilter is a powerful string processing tool.The main function is to split a string into an array (or can be understood as a list) according to the delimiter you specify.Imagine that the user enters multiple keywords in a text box, separated by commas, such as 'Anqi CMS, template development, SEO optimization'.splitwith the filter, we can convert this original string into["安企CMS", "模板开发", "SEO优化"]such data structure, which makes it convenient for us to proceed with subsequent processing and verification.

If the string does not contain the specified delimiter,splitThe filter returns an array containing only the original string itself, with a length of 1.If the specified delimiter is an empty string, it will split each UTF-8 character (including Chinese characters) in the original string into an element of the array.

How to make use ofsplitPerform data validation

Once the original string issplitFilter the array, and we can easily get the length of this array, which is the number of elements the user entered. This issplitThe place where filters excel in data validation scenarios. For example, if we need users to provide at least 2 tags and no more than 5,splitSplit the user input tag string into an array, get its length, and then perform logical judgment based on this length.

We will look at a specific example to see how to implement this verification in the AnQiCMS template in English.We have a form where the user needs to enter article tags, and we require that the number of tags must be between 2 and 5.

{# 假设 user_input_tags 是从用户输入获取的字符串,例如 "标签1, 标签2, 标签3" #}
{% set raw_tags_string = request.query.tags %} {# 从URL查询参数获取,实际应用中可能来自表单字段 #}

{# 使用 split 过滤器将字符串按逗号切割成数组 #}
{# 注意:这里分隔符是 ",",如果用户输入可能有空格,例如 "标签1, 标签2",
   切割后每个元素可能包含前导或尾随空格,后面会提到如何处理。 #}
{% set tags_array = raw_tags_string|split:"," %}

{# 获取切割后的数组长度 #}
{% set tags_count = tags_array|length %}

{# 进行数量验证 #}
{% if tags_count < 2 %}
    <p style="color: red;">您至少需要输入2个标签,当前输入了 {{ tags_count }} 个。</p>
{% elif tags_count > 5 %}
    <p style="color: red;">您最多只能输入5个标签,当前输入了 {{ tags_count }} 个。</p>
{% else %}
    <p style="color: green;">标签数量符合要求:{{ tags_count }} 个。</p>
    <h4>已输入的标签:</h4>
    <ul>
    {% for tag in tags_array %}
        {# 针对每个标签,使用 trim 过滤器去除可能存在的首尾空格,提升用户体验 #}
        {% if tag|trim|length > 0 %} {# 进一步判断去除空格后是否为空字符串 #}
            <li>{{ tag|trim }}</li>
        {% endif %}
    {% endfor %}
    </ul>
{% endif %}

In this template code, we first usesetLabel the original label string (raw_tags_string) by tag reference.splitafter the filter is processed, assign totags_arrayvariable. Then, we gettags_arrayoflengthto get the number of labelstags_count. Finally, throughif/elif/elseLogical judgmenttags_countWhether it meets the requirement of 2 to 5, and gives the corresponding prompt information.

It is worth mentioning that in the traversaltags_arrayWhen outputting each tag, we use an additionaltrimFilter (tag|trim) This is because users might accidentally leave extra spaces when entering (e.g.,splitThe filter will split by the specified delimiter only, and will not automatically remove these spaces.trimThe filter can effectively remove spaces from both ends of a string, making the display more tidy. We also added atag|trim|length > 0check to avoid users entering",,"this continuous separator to produce empty tags.

Some considerations in practice

  • Choice of delimiter: Choose an appropriate delimiter according to the actual user input habits and business requirements. Common ones include comma (,), semicolon (;) or pipe (|English等。If there is a space between the delimiter and the content when the user enters it, thensplitusetrimis a good habit.
  • the handling of empty strings.:As documented, if the user enters an empty string (for example, nothing is filled in),splitthe filter will split it into an array containing an empty string.[""]itslengthIt remains 1. This means that if your validation logic is “at least 1 valid element”, you need to judge each element an extra time intrimAfter whether the length is greater than 0, to filter out invalid empty elements.
  • Client and server-side validationAlthough AnQiCMS template provides powerful data validation capabilities, this is mainly used for immediate friendly user feedback.For strict validation involving data integrity and security, it is usually still recommended to perform it on the backend (server-side) to prevent malicious users from bypassing frontend or template validation.

By using flexibilitysplitFilter and other auxiliary filters, we can build a more robust and user-friendly data input validation mechanism in the AnQiCMS template.


Common Questions (FAQ)

1.splitfilters andmake_listWhat are the differences between filters?

splitThe filter will split the string into an array based on the specification you provide.Separator(such as commas, spaces, etc.) Its purpose is to split structured text content. However,make_listthe filter will split the stringsEvery character(including Chinese characters, letters, numbers, and symbols) is split into an element of an array independently. If you want to split a sentence into words, you should usesplitIf you want to split a word into individual characters,make_listis more appropriate.

2. How to ensure that each element entered by the user does not have extra spaces after splitting?

splitThe filter will only split according to the specified delimiter and will not automatically remove the spaces around each element. To obtain clean elements, you need to use the element in the array after splitting while traversing.trimfilter. For example:{{ tag_item|trim }}It will remove the whitespace characters before and after the elements.

**3. If the user leaves the input box blank,splitwhat will the filter return? How should I handle this situation?