As an experienced website operations expert, I fully understand that even the smallest details can have a huge impact on improving website user experience and ensuring data security. Today, we will delve into a practical and common requirement: how to set the captcha input box as required in the AnQiCMS template (requiredEnsure that the user fills in all necessary information before submitting the form, thus enhancing the usability and data quality of the form.
Improve user experience and form security: Verification code in AnQiCMS templaterequiredAttribute setting guide
In today's internet environment, the security of website forms and user experience are the two cornerstones of successful operation.Whether it is message consultation, user registration, or content comments, a well-designed and functional form can significantly improve user conversion rates and reduce invalid data.AnQiCMS is a powerful content management system developed based on the Go language, which is SEO-friendly and dedicated to providing users with efficient, secure, and scalable content management solutions.It has a flexible template mechanism, especially support for syntax similar to the Django template engine, which allows us to easily customize the front-end page in depth, including adding necessary HTML5 attributes to form elements.
A seemingly trivialrequiredThe property can prevent users from submitting empty forms in the first time, effectively improve the quality of data, and provide immediate operational feedback to users, avoiding unnecessary waiting and confusion. When users try to submit a form that is not filled outrequiredWhen a field's form is filled out, the browser will immediately prompt them to complete the input, which is much more efficient than waiting for the server to return an error message before correcting it, greatly optimizing the user experience.
Enable background captcha feature
Before you start modifying the template, please make sure that the captcha function on your AnQiCMS backend is enabled. This is a prerequisite for the normal operation of the captcha. Usually, you can后台 -> 全局设置 -> 内容设置Find the relevant options, confirm whether the '留言评论验证码功能' has been checked and enabled.Only when this feature is enabled on the backend, the verification code-related code in the front-end template can interact correctly with the backend API, obtain and verify the verification code.
Locate and modify the template file
Next, we need to locate the form template file where you want to add the required captcha attribute.In AnQiCMS, common forms such as message forms or comment forms usually correspond to specific template files.template/您的主题名/guestbook/index.htmlOr (used for the message page)template/您的主题名/comment/list.html(Used for comment lists, which include comment submission forms).You can edit these files online through the "Template Design" feature in the AnQiCMS backend, or directly access the server file system via FTP/SFTP tools.
After finding the corresponding template file, you will see an HTML structure similar to a message form or a comment form. The captcha input box usually has a<input type="text" name="captcha" ...>The element. To add a required attribute, simply in<input>add in therequiredthe keyword.
This is an example of typical code to set the required attribute for the captcha input box in the AnQiCMS template, you can insert it into your form structure, usually after the username, content fields, and before the submit button:
<div style="display: flex; clear: both">
{# 隐藏的验证码ID字段,用于后端验证 #}
<input type="hidden" name="captcha_id" id="captcha_id">
{# 验证码输入框,关键在这里加入了 'required' 属性 #}
<input type="text" name="captcha" required placeholder="请填写验证码" class="layui-input" style="flex: 1">
{# 验证码图片显示区域 #}
<img src="" id="get-captcha" style="width: 150px;height: 56px;cursor: pointer;" />
{# 用于加载和刷新验证码的JavaScript代码 #}
<script>
document.getElementById('get-captcha').addEventListener("click", function (e) {
fetch('/api/captcha') // 向后端API请求验证码
.then(response => {
return response.json()
})
.then(res => {
// 将后端返回的验证码ID设置到隐藏字段
document.getElementById('captcha_id').setAttribute("value", res.data.captcha_id)
// 将后端返回的验证码图片URL设置到图片src
document.getElementById('get-captcha').setAttribute("src", res.data.captcha)
}).catch(err =>{console.log(err)})
});
// 页面加载时自动点击一次,加载初始验证码
document.getElementById('get-captcha').click();
</script>
</div>
Code analysis:
This code contains several core elements:
<input type="hidden" name="captcha_id" id="captcha_id">This is a hidden field used to store the unique identifier ID generated by the backend.When the user submits the form, this ID will be sent to the server along with the user's entered captcha content for verification.<input type="text" name="captcha" required placeholder="请填写验证码" ...>: This is the captcha input box we are concerned about. By addingrequiredthe attribute, it will become a required field.placeholderThe property provides a friendly prompt message.<img src="" id="get-captcha" ...>: This is the area for displaying the captcha image.srcThe property is filled dynamically through JavaScript.id="get-captcha"It is the identifier for this element obtained through JavaScript.- JavaScript code block:
- It passes
document.getElementById('get-captcha').addEventListener("click", ...)Bound a click event listener to the captcha image, which means that when the user clicks on the image, the captcha can be refreshed. fetch('/api/captcha'): This is to the AnQiCMS backend/api/captchaThe interface initiates a request to get a new captcha image and ID..then(res => { ... }): The backend returns the data, tocaptcha_idAssign to the hidden field, and willcaptchaAssign the image URL to<img>label'ssrcProperty.document.getElementById('get-captcha').click();This line of code is very critical, it simulates a click to ensure that the captcha image is automatically loaded and displayed when the page loads, without the need for manual click by the user.
- It passes
If you prefer to use the jQuery library, you can replace the above JavaScript code with the following form:
<script>
// jQuery 调用方式
$('#get-captcha').on("click", function (e) {
$.get('/api/captcha', function(res) {
$('#captcha_id').attr("value", res.data.captcha_id)
$('#get-captcha').attr("src", res.data.captcha)
}, 'json')
})
$('#get-captcha').click(); // 页面加载时自动加载验证码
</script>
Deployment and optimization suggestions
After completing the template modification, please make sure to save the changes and refresh your website cache (AnQiCMS backend has a "Update Cache" feature) to ensure that the new template file takes effect.After refreshing the page, try submitting the form without filling in the captcha, and you will see the required prompts provided by the browser.
Important reminder:
- Client-side validation and server-side validation:Although
requiredThe property provides convenient client-side validation, but as an experienced operations expert, we know that this is not a foolproof strategy.The main purpose of client-side validation is to enhance user experience, prevent invalid submissions, but the real security line is always the secondary validation on the server side (AnQiCMS is default handled).Do not rely solely on client-side validation as the only security measure. - Style optimization: In the example code,
styleThe property is just a basic layout, to ensure the user interface is beautiful, you may also need to make more refined style adjustments to the captcha input box and images through CSS, so that they match the overall style of the website. - User-friendliness:Ensure that the captcha input box is positioned intuitively and easily discoverable in the form, avoiding any negative impact on the user's filling process. Clear and
placeholderText and user operation prompts are also a key to improving the experience.
By following the above steps, you can not only add form captcha input box to AnQiCMS.requiredThe attribute, which implements basic client validation, can also enhance the smooth experience of users when filling out forms, thereby improving the success rate of form submission.