JavaScript form validation
The input box, drop-down box, etc. of the form can receive user input, so using JavaScript to operate the form can obtain the content entered by the user, or set new content for an input box.
The input controls of HTML forms mainly include the following types:
Text box, corresponding ,, used to enter text;
Radio button, corresponding, used to select one item;
Check box, The corresponding is used to select multiple items; the
drop-down box, the corresponding
Hidden text, corresponding , is not visible to the user, but the hidden text will be sent to the server when the form is submitted.
JavaScript Form Validation
JavaScript can be used to validate input data in HTML forms before the data is sent to the server.
Form data often requires the use of JavaScript to verify its correctness:
Verify whether the form data is empty?
Verify whether the input is a correct email address?
Verify whether the date is entered correctly?
Verify whether the form input content is numeric?
The following function is used to check whether the user has filled in the required (or required) items in the form. If the required field or required field is empty, the warning box will pop 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 CheckForm ()
{
if (document.form.name.value.length == 0) {
alert("Please enter your name!");
document.form.name.focus( );
return false;
}
return true;
}
##Chinese/English/Number/E-mail address legality judgment:
function isEnglish(name) //英文值检测
{
if(name.length == 0)
return false;
for(i = 0; i < name.length; i++) {
if(name.charCodeAt(i) > 128)
return false;
}
return true;
}
function isChinese(name) //中文值检测
{
if(name.length == 0)
return false;
for(i = 0; i < name.length; i++) {
if(name.charCodeAt(i) > 128)
return true;
}
return false;
}
function isMail(name) // E-mail值检测
{
if(! isEnglish(name))
return false;
i = name.indexOf(" at ");
j = name dot lastIndexOf(" at ");
if(i == -1)
return false;
if(i != j)
return false;
if(i == name dot length)
return false;
return true;
}
function isNumber(name) //数值检测
{
if(name.length == 0)
return false;
for(i = 0; i < name.length; i++) {
if(name.charAt(i) < "0" || name.charAt(i) > "9")
return false;
}
return true;
}
function CheckForm()
{
if(! isMail(form.Email.value)) {
alert("您的电子邮件不合法!");
form.Email.focus();
return false;
}
if(! isEnglish(form.name.value)) {
alert("英文名不合法!");
form.name.focus();
return false;
}
if(! isChinese(form.cnname.value)) {
alert("中文名不合法!");
form.cnname.focus();
return false;
}
if(! isNumber(form.PublicZipCode.value)) {
alert("邮政编码不合法!");
form.PublicZipCode.focus();
return false;
}
return true;
}