JavaScript implements common form validation functions

Source: Internet
Author: User
Tags date format empty expression functions getdate regular expression client
javascript| Form Validation | functions

Whether it is a dynamic site, or other b/s structure of the system, can not be separated from the form
Forms act as a very important role for the client to submit data to the server.
This begs the question, is the data submitted legal? The problem before us is to validate the data
Ensure that the data submitted is legal. So, we wrote a large stack of validation functions. When we start a new one
Project development, we have to write a lot of validation functions, and then debug this large pile of functions ...

This article will introduce a method to improve the reusability of my Code and improve our development efficiency.

The validation of a form should consist of two parts:
First, determine whether the data entered by the user is legitimate.
Second, it prompts the user why your data is illegal.

So, the function of our common form validation function is to implement:
First, get the user input data GetValue (EL)
Second, verify the user's data Checkform (oform)
IE supports custom attributes, which is the basis of this common function implementation
We can add attributes that describe our information on the form element. It's kind of like XML.
Check property: This property is used to store regular expressions of the legality of the data.
Warning property: This sex is used to store the error message.
Third, return the wrong form hint GoBack (EL)
The trigger event for these three steps is onsubmit, remember to return Checkform (this)
It's toppled if you get it wrong:)
<form >

Here, the whole frame comes out, gets the check property of the form element, obtains the string, constructs the regular expression. And then verify its value. If you submit through validation, if the data is not the rule to get the warning attribute of the form element, Generates a hint. and returns to the form element. The overall framework is also simpler.
All we have to do is write regular expressions!

Next, we'll analyze all the form elements
According to their generality, we divide them into three categories
The characteristics of each type of form are different, and our goal is to write generic.

1. Text Input Box text
<input type= "text" name= "TXT" >
<input type= "password" name= "pwd" >
<input type= "hidden" name= "hid" >
<input type= "File" name= "MyFile" >
<textarea name= "Txts" ></textarea>
2. Single Multiple selection box choose
<input type= "checkbox" Name= "C" >
<input type= "checkbox" Name= "C" >
<input type= "Radio" name= "R" >
<input type= "Radio" name= "R" >
3. Single-Dora pull-down menu Select
<select name= "SEL" ></select>
<select name= "Sels" multiple></select>


Said a bunch of "great principles" is too abstract, the code more convincing!

Check.js js function file
////////////////////////////////////////////////////////////////////////////////
/*
*---------------Common validation checkform (oform) for client forms-----------------
* Function: Universal validation of all form elements.
Use
* <form name= "Form1" >
* <input type= "name=" id "check=" ^s+$ "warning=" ID cannot be empty and cannot contain spaces ">
* <input type= "Submit" >
* </form>
* AUTHOR:WANGHR100 (Grey bean baby. NET)
* email:wanghr100@126.com
* Update:19:28 2004-8-23
* Note: Be careful when writing regular expressions. Don't let "conscientious" have loopholes.
* Implemented features:
* Verify the legality of the Text,password,hidden,file,textarea,select,radio,checkbox
* To be implemented function: the regular table to write a library.
*---------------Common validation checkform (oform) for client forms-----------------
*/
////////////////////////////////////////////////////////////////////////////////

Main function
function Checkform (oform)
{
var els = oform.elements;
Traverse all table elements
for (Var i=0;i<els.length;i++)
{
Whether you need to verify
if (Els[i].check)
{
Gets the regular string of validation
var sreg = Els[i].check;
Gets the value of the form, using the universal value function
var sval = GetValue (Els[i]);
String-> regular expression, case-insensitive
var reg = new RegExp (Sreg, "I");
if (!reg.test (Sval))
{
Validation does not pass, pop-up prompts warning
alert (els[i].warning);
This form element gets the focus, with the universal return function
GoBack (Els[i])
return false;
}
}
}
}

The universal value function is divided into three classes to take the value
Text input box, direct value El.value
Tando, traverse all options to get the number of selected returns the result "00" indicates that two are selected
Single-Multiple Pull-down menu, traversing all options to get the selected number returns the result "0" indicates the selected
function GetValue (EL)
{
To get the type of a FORM element
var stype = El.type;
Switch (stype)
{
Case "Text":
Case "hidden":
Case "Password":
Case "File":
Case "textarea": return el.value;
Case "checkbox":
Case "Radio": Return Getvaluechoose (EL);
Case "Select-one":
Case "Select-multiple": Return Getvaluesel (EL);
}
Get the number of Radio,checkbox selected, with "0" to indicate the number of selected, we write regular time can be passed 0{1,} to indicate the number of selected
function Getvaluechoose (EL)
{
var svalue = "";
Gets the name of the first element and searches for this element group
var tmpels = Document.getelementsbyname (el.name);
for (Var i=0;i<tmpels.length;i++)
{
if (tmpels[i].checked)
{
svalue + = "0";
}
}
return svalue;
}
Get the select number of select, with "0" to indicate the number of selected, we write the regular time can pass 0{1,} to indicate the number of selected
function Getvaluesel (EL)
{
var svalue = "";
for (Var i=0;i<el.options.length;i++)
{
The Select Drop-down Box Prompt option is set to Value= ""
if (el.options[i].selected && el.options[i].value!= "")
{
svalue + = "0";
}
}
return svalue;
}
}

A universal return function that verifies the effect of not passing the return. Three classes to take the value
Text input box, cursor positioned at end of text input box
Tando, the first option gets the focus
Single Multi Pull-down menu, get focus
function GoBack (EL)
{
To get the type of a FORM element
var stype = El.type;
Switch (stype)
{
Case "Text":
Case "hidden":
Case "Password":
Case "File":
Case "textarea": El.focus (); var rng = El.createtextrange (); Rng.collapse (FALSE); Rng.select ();
Case "checkbox":
Case "Radio": var els = document.getelementsbyname (el.name); Els[0].focus ();
Case "Select-one":
Case "Select-multiple": El.focus ();
}
}


Demo.htm Demo File

<script language= "JavaScript" src= "Check.js" ></script>
Common form function test:
<form name= "Form1" >
Test:<input type= "text" name= "test" > Do not validate <br>
Account: <input type= "text" check= "^s+$" warning= "account cannot be empty and cannot contain spaces" name= "id" > cannot be empty <br>
Password: <input type= "password" check= "s{6," warning= "password more than six" name= "id" > six-bit <br>
Tel: <input type= "text" check= "^d+$" warning= "phone number contains illegal characters" Name= "No." Value= "" ><br>
Photo Upload: <input type= "File" check= "(. *) (. Jpg|. BMP) $ "warning=" photo should be jpg,bmp format "name=" Pic value= "1" ><br>
Date of birth: <input type= "text" check= "^d{4}-d{1,2}-d{1,2}$" warning= "date format 2004-08-10" name= "DT" value= "" > Date format 2004-08-10<br>
Provinces:
<select name= "sel" check= "^0$" warning= "Please select the province" >
<option value= "" > Please Select
<option value= "1" > Fujian Province
<option value= "2" > Hubei Province
</select>
<br>
Choose the sports:<br> you like
Swimming <input type= "checkbox" Name= "C" check= "^0{2,}$" warning= "Please select 2 or more" >
Basketball <input type= "checkbox" Name= "C" >
Soccer <input type= "checkbox" Name= "C" >
Volleyball <input type= "checkbox" Name= "C" >
<br>
Your education:
University <input type= "Radio" name= "R" check= "^0$" warning= "Please select a degree" >
Middle School <input type= "Radio" name= "R" >
Primary <input type= "Radio" name= "R" >
<br>
Personal Introduction:
<textarea name= "txts" check= "^[s| s]{20,}$ "warning=" personal introduction can not be empty, and not less than 20 words "></textarea>20 word above
<input type= "Submit" >
</form>

JS to determine the correctness of the input dates in both formats

The simplest of

function Isvaliddate (DATESTR) {
var Matcharray = Datestr.match (/^[0-9]+-[0-1][0-9]-[0-3][0-9]$/)
if (Matcharray = = null) {
Alert ("Invalid Date:" + datestr);
return false;
}
return true;
}

Second Kind
<script language=javascript>
String.prototype.isDate = function ()
{
var r = This.match (/^ (\d{1,4}) (-|\/) (\d{1,2}) \2 (\d{1,2}) $/);
if (r==null) return false; var d = new Date (r[1], r[3]-1, r[4]);
Return (D.getfullyear () ==r[1]&& (D.getmonth () +1) ==r[3]&&d.getdate () ==r[4]);
}
Alert ("2002-01-31". IsDate ());
Alert ("2002-01-41". IsDate ());
</script>

The third, more complicated.

<script language=javascript>
String.prototype.isTime = function ()
{
var r = This.match (/^ (\d{1,4}) (-|\/) (\d{1,2}) \2 (\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2);
if (r==null) return false; var d = new Date (r[1], r[3]-1,r[4],r[5],r[6],r[7]);
Return (D.getfullyear () ==r[1]&& (D.getmonth () +1) ==r[3]&&d.getdate () ==r[4]&&d.gethours () = =r[5]&&d.getminutes () ==r[6]&&d.getseconds () ==r[7]);
}
Alert ("2002-1-31 12:34:56". Istime ());
Alert ("2001-2-29 12:54:56". Istime ());
Alert ("2002-1-41 12:00:00". Istime ());
</script>

Judge the number with isNaN ()



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.