Why is front-end client-side validation needed?
Let's talk about the importance of front-end client-side validation.You might ask, doesn't AnQiCMS already have a rigorous verification mechanism on the backend?Indeed, server-side validation is the last line of defense for data security and system stability, and any submitted data must be validated by the backend.
- Enhance user experience:Imagine that the user has filled out a lot of information and clicked submit, only to find out that the format of a certain field is incorrect. At this point, it is necessary to reload the page and wait for the backend response, which undoubtedly brings frustration.Client-side validation can immediately point out errors, allowing users to make corrections immediately, greatly enhancing the fluidity and satisfaction of the operation.
- Relieve server load:Client-side validation filtered out some information that does not meet the requirements before the data reaches the server.This means that the server does not need to process these invalid requests, thereby reducing the server load and improving overall performance.
- Reduce network transmission:Invalid data is intercepted before submission, avoiding unnecessary network transmission. This is particularly important for mobile devices or users with poor network conditions.
Of course, please make sure to remember that client-side validation is merely a 'friendly reminder' to enhance user experience, and it cannot replace the security of server-side validation.Malicious users can bypass frontend validation and send requests directly to the backend, therefore, server-side validation must always be strictly maintained.
Understanding the AnQiCMS comment form structure
In AnQiCMS, the comment form is usually through{% guestbook fields %}
When{% guestbook fields %}The tag is parsed and outputs a similar HTML structure like this (simplified example):
<form method="post" action="/guestbook.html" id="guestbookForm">
<!-- ... 省略其他字段 ... -->
<div>
<label>用户名</label>
<div>
<input type="text" name="user_name" required placeholder="请填写您的昵称" autocomplete="off">
</div>
</div>
<div>
<label>联系方式</label>
<div>
<input type="text" name="contact" required placeholder="请填写您的手机号或微信" autocomplete="off">
</div>
</div>
<div>
<label>留言内容内容</label>
<div>
<textarea name="content" placeholder="" id="comment-content-field" rows="5"></textarea>
</div>
</div>
<!-- ... 其他自定义字段 ... -->
<div>
<div>
<button type="submit">提交留言</button>
<button type="reset">重置</button>
</div>
</div>
</form>
Please note that each form element has anameAttributes, this is the key we use in JavaScript to locate and get its value.typeproperty (such astext/number/textareaetc. andrequiredAttributes also give us some basic hints. The form'sactionAttributes usually point to/guestbook.htmlThis is the built-in interface of AnQiCMS.
Implement the strategy of client-side validation through JavaScript.
Now, let's build our client-side validation logic step by step.
Step 1: Prepare the template file and JavaScript file
Firstly, you need to locate the page file that contains the comment form in your website template, usuallyguestbook/index.html(based on}design-director.mdThe conventions of the document). In this HTML file, we must not only ensure that the comment form is rendered correctly but also introduce our JavaScript validation script.
Suppose you place a custom JavaScript file inpublic/static/js/directory, namedguestbook-validation.js. Then, before theguestbook/index.htmlparts of the</body>tag, you can use the following method to include:
<!-- guestbook/index.html 模板文件片段 -->
<form method="post" action="/guestbook.html" id="guestbookForm">
<!-- ... 您的表单字段由 {% guestbook fields %} 标签生成 ... -->
</form>
<script src="{% system with name='TemplateUrl' %}/js/guestbook-validation.js"></script>
Here we used{% system with name='TemplateUrl' %}Translate the dynamic acquisition of template static file addresses using tags and ensure the path is correct.
Step two: Obtain form elements and bind event listeners.
Inpublic/static/js/guestbook-validation.jsIn the file, we first need to obtain the form itself and prevent its default submission behavior so that we can perform custom validation before submission.
document.addEventListener('DOMContentLoaded', function() {
const guestbookForm = document.getElementById('guestbookForm'); // 获取表单元素
if (guestbookForm) {
guestbookForm.addEventListener('submit', function(event) {
event.preventDefault(); // 阻止表单默认提交行为
let isValid = true; // 标志位,表示表单是否通过验证
// 在这里添加您的验证逻辑
if (isValid) {
// 如果所有验证都通过,则手动提交表单
guestbookForm.submit();
} else {
// 如果验证失败,可以给出提示,例如滚动到第一个错误位置
alert('请检查您的输入,有错误需要修正。');
}
});
}
});
DOMContentLoadedEnsure that the script executes only after the DOM has loaded to prevent errors caused by HTML elements not being ready.
Step 3: Write detailed validation logic and provide user feedback.
Now, we can addguestbookForm.addEventListener('submit', ...)specific validation rules in the callback function. To provide a better user experience, we should display error messages next to each field that requires validation.
We can write some auxiliary functions to display and clear error messages:
`javascript // guestbook-validation.js file content example
// Helper function: Display error message function showError(field, message) {
let errorElement = field.nextElementSibling; // 假设错误消息元素紧跟在输入字段后面
if (!errorElement || !errorElement.classList.contains('error-message')) {
errorElement = document.createElement('div');
errorElement.classList.add('error-message');
field.parentNode.insertBefore(errorElement, field.nextElementSibling); // 插入到字段后面
}
errorElement.textContent = message;
errorElement.style.color = 'red';
field.classList.add('is-invalid'); // 添加一个类名表示字段无效
}
// Helper function: Clear error message function clearError(field) {
const errorElement = field.nextElementSibling;
if (errorElement && errorElement.classList.contains('error-message')) {
errorElement.textContent = '';
errorElement.style.color = '';
}
field.classList.remove('is-invalid');
}
document.addEventListener('DOMContentLoaded', function() {
const guestbookForm = document.getElementById('guestbookForm');
if (guestbookForm) {
guestbookForm.addEventListener('submit', function(event) {
event.preventDefault();
let isValid = true;
// 1. 验证用户名 (name="user_name")
const userNameField = guestbookForm.querySelector('[name="user_name"]');
if (userNameField) {
clearError(userNameField);
if (userNameField.value.trim() === '') {
show