Client form validation is crucial – it saves time and bandwidth and provides more options to point out where users make mistakes when filling out forms. That being said, this doesn't mean you don't need server-side verification. Users visiting your website may have used an old browser or disabled JavaScript, which will break client-only verification. Client and server-side verification complement each other, so they really should not be used independently.
Why is client verification important?
There are two good reasons to use client authentication:
-
It is a quick way to verify: if something goes wrong, an alert will be triggered when the form is submitted.
-
You can safely display only one error at a time and focus on the wrong fields to help ensure that the user fills in all the details you need correctly.
Two main verification methods
The two main methods of client form verification are:
- Show an error at a time, focus on the problematic fields
- Show all errors at the same time, server-side verification style
While displaying all errors at the same time is necessary for server-side verification, a better way to verify client is to display one error at a time. This makes it possible to highlight only fields that have been filled incorrectly, which in turn makes it easier for visitors to modify and submit the form successfully. If you present all the errors to the user at the same time, most people will try to remember and correct them at once, rather than trying to resubmit after each correction.
Given these advantages, I will focus only on the verification method that shows one error at a time.
How to verify the form
For example, the following code snippet:
<code><br> function validateMyForm() { <br> if (parseInt(document.forms[0].phone.value) <br> != document.forms[0].phone.value) { <br> alert('请输入电话号码,仅限数字'); <br> return false; <br> } <br> <br> return true; <br> } <br> <br><br></code>
Tel:
What's the problem? Well, if you add another form before this, the code will try to validate the wrong form.
A better way is to include the form name:
<code>function validateMyForm() { <br> if (parseInt(document.forms.myForm.phone.value) <br> != document.forms.myForm.phone.value) { <br><br></code>
onsubmit="return validateMyForm();"> This is certainly better, but still not portable enough - if you want to reuse part of this validation on another form, you have to do a lot of text replacement first.
So let's delete the form name:
<code>function validateMyForm(form) { <br> if (parseInt(form.phone.value) != form.phone.value) { <br><br></code>
This last method uses the object this, which always points to the current object. This makes our code more portable and saves typing time.
How to make the life of visitors easier now? Let's focus on the fields that trigger the error, rather than letting them look it up on their own.
<code>function validateMyForm(form) { <br> if (parseInt(form.phone.value) != form.phone.value) { <br> alert('请输入电话号码,仅限数字'); <br> form.phone.focus(); <br> form.phone.select(); <br> return false; <br> }</code>
With these changes, the browser will focus on filling in incorrect fields and will even select text for the visitor. This will also happen automatically if scrolling is required.
OK, this is great, but do you think there is a bit too much code for each field? What if we create a simple library of functions that can save a lot of typing and downloading time on the page? Well, next we'll do this - we'll define our basic functions to make the validation code shorter.
<code><br> function validateMyForm() { <br> if (parseInt(document.forms[0].phone.value) <br> != document.forms[0].phone.value) { <br> alert('请输入电话号码,仅限数字'); <br> return false; <br> } <br> <br> return true; <br> } <br> <br><br></code>
This function performs a simple verification of numbers - it checks whether the field contains only numbers and optionally, whether it is within a given range. You will notice that this code passes an error message as a parameter. To use a function like this, we can basically add it to the onsubmit handler as follows:
<code>function validateMyForm() { <br> if (parseInt(document.forms.myForm.phone.value) <br> != document.forms.myForm.phone.value) { <br><br></code>
onsubmit="return validateNumber(this.phone,
'Please enter the phone number, only numeric', 5, 10);"> Call it like this, it will check if the phone number is a numeric and is longer than 5 digits and less than 10 digits. Note how to pass the phone object as a parameter? This allows us to focus on it through helper functions instead of just passing the value of the field.
Another way to verify numbers is to require them to be within a given range. To make the function perform such validation, just change the check line to:
<code>function validateMyForm(form) { <br> if (parseInt(form.phone.value) != form.phone.value) { <br><br></code>
If you want to apply multiple checks to a form, you can embed multiple rules in the onsubmit handler. For example, imagine that in addition to the phone number, we also need to enter our first and last name:
<code>function validateMyForm(form) { <br> if (parseInt(form.phone.value) != form.phone.value) { <br> alert('请输入电话号码,仅限数字'); <br> form.phone.focus(); <br> form.phone.select(); <br> return false; <br> }</code>
onsubmit="return (
validateNumber(this.phone, 'Please enter the phone
Number, number only', 5, 10) &&
validateString(this.firstName, 'Please enter
Your name', 3, 15) &&
validateString(this.lastName, 'Please enter
Your last name', 3, 15)
);"> The code requires that all validation rules be evaluated as true (using logic AND - &&). A closer look shows that it is very easy to generate such code from the server scripting language...but this is another article.
<code>function validateNumber(field, msg, min, max) { <br> if (!min) { min = 0 } <br> if (!max) { max = 255 } <br> <br> if ( (parseInt(field.value) != field.value) || <br> field.value.length max) { <br> alert(msg); <br> field.focus(); <br> field.select(); <br> return false; <br> } <br> <br> return true; <br> }</code>
As you can see, string validation functions look more or less the same; you can also write other functions and use them in conjunction with these functions.
A common field is required in many forms on the Web, namely the user's email address. I've seen a lot of functions that do this, but usually the easiest and easiest way to verify email addresses is by using regular expressions.
Now we will extend our function so that it can define fields as optional.
<code></code>
To verify the required email, you should call it as:
<code>if ((parseInt(field.value) != field.value) || <br> field.value max) {</code>
If you want to set it to optional:
<code></code>
JavaScript cannot be used for verification alone, but it can be of great help if you have it. The more compact the code you embed into HTML, the better – it saves download time and search engines will like you!
Frequently Asked Questions about Form Verification (FAQ)
What is the difference between client verification and server-side verification?
Client verification is performed in the user's browser using JavaScript before form data is sent to the server. It provides instant feedback and improves the user experience. However, it can be bypassed by disabling JavaScript or manipulating the code, so it is not completely safe.
On the other hand, server-side verification is performed on the server after submitting the form data. It's safer because users can't bypass it. However, it requires a round trip to the server, which can affect performance and user experience. Therefore, it is recommended to use both client and server-side verification for the best security and user experience.
How to implement form validation in PHP?
PHP provides a variety of form validation functions. For example, you can use the filter_var() function with different filters to validate and clean the input data. Here is a simple example of verifying an email address:
$email = $_POST["email"]; if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { echo "Invalid email format"; } This code checks if the submitted email address is formatted correctly. If not, an error message is displayed.
What are some common verification techniques?
Some common verification techniques include required fields, length limits, pattern matching, and data type checking. Required fields ensure that the user fills in all necessary information. Length limits limit the number of characters that can be entered. Pattern Match Checks if the input matches a specific pattern, such as an email address or phone number. Data type checking ensures that the input is the correct type, such as a number or date.
How to display verification error message?
You can use JavaScript for client verification or server-side verification using PHP to display verification error messages. In JavaScript, you can use the setCustomValidity() method to set up a custom validation message. In PHP, you can store error messages in variables and display them in a form.
How to verify the checkbox?
You can verify the check box by checking whether the check box is selected. In JavaScript, you can use the checked property. In PHP, you can check whether the checkbox value appears in $_POST or $_GET.
How to verify the drop-down list?
You can verify the drop-down list by checking whether the valid option is selected. In JavaScript, you can use the selectedIndex property. In PHP, you can check if the selected value is in an array of valid values.
How to verify radio buttons?
You can verify the radio button by checking whether one of the options is selected. In JavaScript, you can loop through the radio buttons and use the checked property. In PHP, you can check if the radio button value appears in $_POST or $_GET.
How to verify the date?
You can verify the date by checking if the date is formatted correctly and if it is a real date. In JavaScript, you can use the Date object. In PHP, you can use the checkdate() function.
How to verify file upload?
You can verify file uploads by checking file size, file type, and file extension. In JavaScript, you can use the files property. In PHP, you can use the $_FILES array.
How to prevent SQL injection?
You can prevent SQL injection using preprocessed statements or parameterized queries that separate SQL code from data. This prevents the data from being interpreted as code. In PHP, you can use PDO or MySQLi extensions to execute preprocessing statements.
The above is the detailed content of Form Validation on the Client Side. For more information, please follow other related articles on the PHP Chinese website!

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver Mac version
Visual web development tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6
Visual web development tools

Atom editor mac version download
The most popular open source editor

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.
