Home >Web Front-end >JS Tutorial >Form Validation on the Client Side
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.
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.
The two main methods of client form verification are:
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.
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!
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.
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.
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.
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.
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.
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.
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.
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.
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.
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!