1. Introduction
Form verification is crucial in front-end development. It not only improves the user experience, but also reduces the entry of wrong data into the back-end and enhances security. Verification is usually divided into two categories: client authentication and server authentication. Front-end verification mainly detects whether the input is legal before the user submits data. Through reasonable policies and tools, unnecessary network requests and back-end pressure can be reduced. This article will introduce a variety of front-end form verification methods, best practices and common pitfalls to help you build a robust and friendly verification system.
2. Overview of verification methods
2.1 HTML5 native verification
HTML5 provides some built-in verification properties that enable basic verification without JavaScript:
- required: Required fields
- pattern: Regular expression matching
- min/max、minlength/maxlength: numerical or character length limit
- type: Automatic verification format for specific types (email, number, url, etc.)
Example:
<form> <input type="text" name="username" required minlength="3" maxlength="20" pattern="[a-zA-Z0-9]+" title="Only include letters and numbers"> <input type="email" name="email" required> <input type="password" name="password" required minlength="6"> <button type="submit">submit</button> </form>
2.2 JavaScript custom verification
For complex business logic, pure HTML verification may not meet the needs. With JavaScript, you can provide real-time feedback and dynamic adjustment of verification rules.
-
Event listening:use
oninput
、onblur
oronsubmit
Listen to user input - Regular expressions: Match for specific formats
- Error message: Dynamically modify the DOM to display error message
Example:
<form > <label for="username">username:</label> <input type="text" placeholder="3-20 letters or numbers"> <span class="error"></span> <button type="submit">submit</button> </form> <script> ("myForm").addEventListener("submit", function(event) { let username = ("username").value; let errorSpan = ("usernameError"); let isValid = true; if (!/^[a-zA-Z0-9]{3,20}$/.test(username)) { = "Username format is incorrect"; isValid = false; } else { = ""; } if (!isValid) { (); // Block submission } }); </script>
2.3 Using third-party verification library
For large projects, third-party libraries can greatly improve verification efficiency and code maintainability. For example:
- Yup: Declarative object verification library, integrated with Formik
- VeeValidate: Form Verification Plugin for Vue
- Formik: Form management library for React, often used in conjunction with Yup
React + Formik + Yup Example:
import React from 'react'; import { useFormik } from 'formik'; import * as Yup from 'yup'; const SignupForm = () => { const formik = useFormik({ initialValues: { username: '', email: '' }, validationSchema: ({ username: () .matches(/^[a-zA-Z0-9]+$/, "Only include letters and numbers") .min(3, "At least 3 characters") .max(20, "Maximum 20 characters") .required("Username Required"), email: ().email("Invalid Email").required("Email required"), }), onSubmit: values => { alert((values, null, 2)); }, }); return ( <form onSubmit={}> <div> <label>username</label> <input type="text" name="username" onChange={} onBlur={} value={} /> { && ? ( <div className="error">{}</div> ) : null} </div> <div> <label>Mail</label> <input type="email" name="email" onChange={} onBlur={} value={} /> { && ? ( <div className="error">{}</div> ) : null} </div> <button type="submit">submit</button> </form> ); }; export default SignupForm;
3. Best practices for form validation
3.1 Front and back end dual verification
While front-end verification can provide instant feedback, it does not guarantee data security. Verification should always be performed again on the backend to prevent malicious requests that bypass the front-end verification.
3.2 Real-time feedback and user experience
- Instant feedback: Provide error prompts when user inputs to reduce repeated modifications during submission.
- Friendly Tips: The error message should be clear and specific, telling the user how to correct input errors.
- Auxiliary input: Enhance the user experience with automatic completion, placeholders, input formatting, etc.
3.3 Accessibility considerations
Ensure that error prompts and verification information can be read by screen readers, and the form controls should have correct label associations.
- use
aria-live
Regional dynamic feedback error message. - Ensure that form controls have corresponding
label
Label.
3.4 Modularization and multiplexing
Encapsulate commonly used verification rules into reusable functions or components to reduce code redundancy. For example, regular verification functions that encapsulate mobile phone numbers and email addresses can be reused in different forms.
3.5 Data format and regular expressions
Ensure that the regular expression is designed reasonably, covering most reasonable input scenarios, and allowing users to make appropriate corrections. Debugging can be done using online tools such as Regex101.
4. Common pit points and debugging skills
4.1 Ignore browser native verification
Some browsers trigger built-in verification by default when submitting forms (such as Chrome's native prompts). If custom verification conflicts with native verification, it may cause confusion to users. Can be passednovalidate
Properties disable native verification:
<form novalidate> <!-- Form content --> </form>
4.2 Asynchronous Verification
Some scenarios require remote verification (such as checking whether the username is duplicated), and the verification status needs to be updated after the asynchronous request is completed. Make sure to handle asynchronous logic well and prevent state update delays or race conditions.
4.3 Confused state management
When using React, Vue and other frameworks, form state may become complicated. It is recommended to use a special status management scheme (such as Formik and VeeValidate) to centrally manage verification status and error prompts.
4.4 Compatibility Testing
Make sure to test the validation effect on different devices and browsers. Due to differences in CSS and JavaScript, some interactions may behave inconsistently in some browsers.
5. Summary
Key strategies for handling front-end form verification to ensure that user input is legitimate include:
-
Leverage HTML5 native verification:pass
required
、pattern
etc. for basic verification. - Custom JavaScript Verification: Listen to user input in real time, use regular expressions and logical judgments to verify, and dynamically feedback error information.
- Using third-party libraries: Use Formik, Yup, VeeValidate and other tools to simplify verification process and status management in complex projects.
- Front and backend double verification: Front-end verification improves user experience, and back-end verification ensures data security.
- Optimize user experience and accessibility: Instant feedback, clear error prompts and auxiliary input to ensure that all users (including people with disabilities) can use the form smoothly.
- Debugging and testing: Use browser developer tools, regular expression debugging tools and cross-browser testing to ensure that the verification logic is robust.
This is the article about how to deal with front-end form verification to ensure that user input is legal. For more relevant front-end form verification, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!