In website operation, the comment feature is an important part of user interaction.To maintain a good community environment and data quality, we usually limit the length of comments submitted by users.The front-end validation plays a key role in this process, it can provide immediate feedback before submission by the user, avoiding failure due to content overlength, thereby improving user experience and reducing server load.

How can we judge the user comment content in a website built using AnQiCMS (AnQiCMS)comment.ContentIs the length exceeding the limit, and can it be validated on the front end? This can actually be achieved through some built-in attributes of HTML5 and simple JavaScript code.

Understand the comment content length limit

Assuming we added a parameter named in the "Global Settings" -> "Custom Setting Parameters" of the Anqi CMS backend,CommentMaxLengthThe parameter, and set its value to the maximum number of characters for the comment content we hope to have, for example200. This way, the front-end can obtain this dynamic value through the template tags provided by the CMS.

Skillfully Utilize HTML5maxlengthProperty

The simplest and most fundamental front-end validation method is to use HTML5'smaxlengthattribute. This attribute can be directly added to<textarea>标签上,它会自动限制用户在文本框中可以输入的字符数量。当用户输入超过这个限制时,浏览器会阻止额外的输入。

In our comment form, find the input field for entering comments.<textarea>Label. By combining the template tags of Anqi CMS, we can set it up like this:

<textarea
  name="content"
  placeholder="请输入您的评论(限{{ system.CommentMaxLength }}字)"
  id="comment-content-field"
  rows="5"
  maxlength="{{ system.CommentMaxLength }}"
></textarea>

Here,maxlength="{{ system.CommentMaxLength }}"will be set according to our backend settings.CommentMaxLengthThe value is dynamically inserted intotextareaofmaxlengthProperties. In this way, even if the backend modifies the length limit, the frontend will automatically synchronize the update without modifying the code. At the same time, we also gave the user a friendly reminder of this limit information.

JavaScript Real-time Validation: Provide more flexible feedback

HTML5maxlengthThe attribute is convenient, but it only provides input limits and lacks more comprehensive user feedback, such as how many characters have been entered, how many characters are left, and how many characters have been exceeded, etc.This is where we need to use JavaScript to implement more detailed real-time validation.

We can write a JavaScript code to listen for the input event of the user in the review text box (for example,inputorkeyupEvent), then calculate the number of characters entered in real time, and compare it with the set maximum length to provide visual feedback.

To make JavaScript code also be able to dynamically obtain the maximum length, we can addtextareaan extradata-attribute to store this value:

<textarea
  name="content"
  placeholder="请输入您的评论(限{{ system.CommentMaxLength }}字)"
  id="comment-content-field"
  rows="5"
  maxlength="{{ system.CommentMaxLength }}"
  data-maxlength="{{ system.CommentMaxLength }}"
></textarea>
<div id="comment-length-feedback">您已输入 <span>0</span> 字,还可输入 <span>{{ system.CommentMaxLength }}</span> 字。</div>
<div id="comment-error-message" style="color: red; display: none;">评论内容超出限制!</div>

Then, we can add the following JavaScript code:

document.addEventListener('DOMContentLoaded', function() {
    const commentField = document.getElementById('comment-content-field');
    const feedbackElement = document.getElementById('comment-length-feedback');
    const errorMessage = document.getElementById('comment-error-message');
    const maxLength = parseInt(commentField.getAttribute('data-maxlength') || '200', 10); // 默认200字

    // 初始化显示
    updateFeedback(commentField.value.length);

    commentField.addEventListener('input', function() {
        const currentLength = this.value.length;
        updateFeedback(currentLength);

        if (currentLength > maxLength) {
            errorMessage.style.display = 'block';
            commentField.style.borderColor = 'red'; // 视觉提示
            // 可以选择禁用提交按钮
            // document.querySelector('button[type="submit"]').disabled = true;
        } else {
            errorMessage.style.display = 'none';
            commentField.style.borderColor = ''; // 恢复边框颜色
            // document.querySelector('button[type="submit"]').disabled = false;
        }
    });

    function updateFeedback(currentLength) {
        const remaining = maxLength - currentLength;
        feedbackElement.innerHTML = `您已输入 <span>${currentLength}</span> 字,还可输入 <span>${remaining}</span> 字。`;

        // 如果剩余字数小于0,改变颜色提示
        if (remaining < 0) {
            feedbackElement.style.color = 'red';
        } else {
            feedbackElement.style.color = '';
        }
    }
});

This JavaScript code will execute after the page has finished loading:

  1. It first retrieves the DOM elements of the comment text box, feedback information, and error messages.
  2. From the text box ofdata-maxlengthRead the maximum length limit in the property, if the acquisition fails, it will fallback to the default value (for example, 200).
  3. inputThe event listener will trigger every time the user enters or deletes a character.
  4. In the event handling function, it calculates the current length of the text.
  5. updateFeedbackThe function is used to update the display of the number of characters entered and the number of characters that can still be entered, and adjusts the display color based on the remaining number of characters.
  6. If the current length exceedsmaxLengthIf an error message is displayed, the text box border will turn red, providing a direct visual warning. At the same time, you can also choose to disable the submit button to prevent users from submitting content beyond the limit.

Improve user experience: Details determine success or failure

In addition to the core length judgment, there are some details that can further improve user experience:

  • Clear prompt text: IntextareaofplaceholderExplicitly inform users of the word limit.
  • Live word count statisticsThe "You have entered XX words, you can still input YY words" implemented by JavaScript can help users better control their input.
  • Visual feedbackWhen exceeding the limit, the text box border changes color, and error information is displayed in red, all of which can attract the user's attention in the first time.
  • Disable the submit buttonIn case the content does not meet the requirements, disable the submit button, which can effectively prevent invalid submissions and reduce user frustration.
  • Consider multilingual supportIf your AnQi CMS website supports multi-language, these prompt texts should also be translated through the AnQi CMS translation tags{% tr %}to achieve multi-language switching.

By means of the above method, we can combine the configuration capabilities of the Anqi CMS backend with the HTML5 features and JavaScript dynamic validation, providing a comprehensive and user-friendly front-end length validation mechanism for the user comment feature.This not only improves the user experience, but also ensures the standardization of website content.


Common Questions (FAQ)

Q1: If JavaScript is disabled by the user, will front-end validation still work?A1: If the user has disabled JavaScript, HTML5'smaxlengthThe property will still take effect. The browser will prevent the user from entering characters beyond the specified length, but real-time word count and custom error messages will not be displayed. Therefore,maxlengthThe attribute is a good basic guarantee.

Q2: Is front-end validation sufficient? Do we need back-end validation as well?A2: Absolutely need backend validation.The main purpose of front-end validation is to enhance user experience and provide immediate feedback, but it is not a secure ultimate barrier.Malicious users or users with technical expertise can easily bypass frontend validation.All critical data validation, including comment length and content validity, must be validated again on the server side to ensure the integrity and security of the data.

Q3: Can this front-end validation method be applied to other form fields in addition to the comment content length?A3: Of course, you can.This front-end validation approach has strong universality.maxlengthTo implement real-time, friendly frontend validation using properties and similar JavaScript logic.Just set the custom maximum length parameter for the corresponding field in the "Global Settings" of the Anqi CMS backend, and then refer to it in the front-end template and JavaScript.