May 06, 2021 JavaScript
JavaScript can be used to validate the input data in HTML forms before it is sent to the server.
Form data often needs javaScript to verify its correctness:
The following function checks whether the user has filled out the required (or required) items in the form. If the required or required option is empty, the warning box pops up and the return value of the function is false, otherwise the return value of the function is true (meaning there is no problem with the data):
function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
}
The above function is called when the form form is submitted:
The following function checks whether the data entered conforms to the basic syntax of the e-mail address.
This means that the data entered must contain the sign and dot (.). At the same time, the first character of the e-mail address must not be the first character, and the s must be followed by at least one dot:
function validateForm()
{
var x=document.forms["myForm"]["email"].value;
var atpos=x.indexOf("@");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Not a valid e-mail address");
return false;
}
}
Here's the full code along with the HTML form:
The following function checks whether the input data is a number between 1 and 10. If you do not enter a number or not, the warning box pops up and the return value of the function is false, otherwise the return value of the function is true (meaning there is no problem with the data):
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm();" method="post">
<strong>请输入1到10之间的数字:</strong>
<input id="number">
<button type="button" onclick="myFunction()">提交</button>
</form>
JavaScript Standard Reference Tutorial: JavaScript Form