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!

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.

JavaScript does not require installation because it is already built into modern browsers. You just need a text editor and a browser to get started. 1) In the browser environment, run it by embedding the HTML file through tags. 2) In the Node.js environment, after downloading and installing Node.js, run the JavaScript file through the command line.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

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.

Atom editor mac version download
The most popular open source editor

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),