Home > Article > Web Front-end > How to use JavaScript to implement web form validation?
How to use JavaScript to implement web form verification?
As one of the basic elements of web development, forms play an important role in web pages. When users interact with web pages, through forms, users can enter, submit, and modify data. However, the data entered by users is not always accurate, so it is necessary to add form validation function to the web page. This article will introduce how to use JavaScript to implement web form validation and provide specific code examples.
const form = document.querySelector('#myForm');
form.addEventListener('submit', function(event) { event.preventDefault(); // 在这里进行表单验证 });
const input = document.querySelector('#username'); if (input.value === '') { // 输入为空 }
const input = document.querySelector('#password'); if (input.value.length < 6) { // 输入长度不足 }
const input = document.querySelector('#email'); const emailPattern = /^w+@[a-zA-Z_]+?.[a-zA-Z]{2,3}$/; if (!emailPattern.test(input.value)) { // 格式不匹配 }
const errorDiv = document.createElement('div'); errorDiv.textContent = '输入错误'; form.insertBefore(errorDiv, form.firstElementChild);
The complete sample code is as follows:
const form = document.querySelector('#myForm'); const input = document.querySelector('#username'); const emailPattern = /^w+@[a-zA-Z_]+?.[a-zA-Z]{2,3}$/; form.addEventListener('submit', function(event) { event.preventDefault(); //必填字段验证 if (input.value === '') { showError('用户名不能为空'); return; } //格式匹配验证 if (!emailPattern.test(input.value)) { showError('请输入有效的电子邮件地址'); return; } //表单验证通过,提交表单 form.submit(); }); function showError(message) { const errorDiv = document.createElement('div'); errorDiv.textContent = message; form.insertBefore(errorDiv, form.firstElementChild); }
The above is a simple example of using JavaScript to implement web form verification function. Through the above steps, we can easily add validation functions to web forms and provide users with corresponding error messages to improve user experience and data accuracy.
The above is the detailed content of How to use JavaScript to implement web form validation?. For more information, please follow other related articles on the PHP Chinese website!