Simple and practical Form verifier

Source: Internet
Author: User
Tags filter date format final functions getdate time and date tostring
Form Validation | programs

Look at the Hermit form verification, and looked at some other validation procedures and related references, wrote a relatively concise JS form verification program.

function Brief :

Verify:

    • HTTP address
    • Time and date
    • E-Mail
    • Digital
    • Character length Check
    • One entry compares to another entry (for example, confirmation input for a password)
    • Size comparison (only one comparison symbol)

Characteristics

    • Easy to expand and easily add the authentication you need
    • Good compatibility (ie5,6 Firefox,oprea)
    • Availability is good, no alert () is used to eject the prompt

Writing Ideas :

The structure of the whole program and simpler, in order to be able to verify some commonly used formats, first of all JS built-in objects are extended. Like what:

STRING.PROTOTYPE.ISURL = function () {
var url =/^http:\/\/[a-za-z0-9]+\. [a-za-z0-9]+[\/=\?%\ -&_~ ' @[\]\ ': +!] * ([^<>\ "\"]) *$/;
var tmpstr = this;
Return Url.test (TMPSTR);
}

This is used to verify the HTTP address.

And then write an object called Vform contains the main features that, when initialized, check for added validation rules and extend the form control object that will be validated, adding validate () and validlength () two functions, and add the onblur event to validate.
Error prompted the use of the method of creating a Div object, the error is displayed, the correct hidden. So you also need to define a style for the Div.
You need to specify the ID of the form before you use it is ID is not name or there is an error, and the rule is added to specify that the form control's Name property is not an ID

Validation Rule parameters:

obj-Form Control Name

minlength-fill in the string minimum length of 0 means that you can not fill in and 1 means is required to add

The datatype-authentication format has

    • E-Mail
    • Url
    • Date
    • Number
    • Any
    • There are also two dynamic formats that start with \, and the name of the form control must be the same as its value;
    • \> numbers represent greater than numbers, and so on; but there's no such thing as \>=.

maxlength-maximum length.

Unlike other programs: I am dealing with the HTTP address and date format address is different, fill in the address does not http://I will add after verification, so more humane, meet the requirements of usability. Date processing is the same, first as far as possible to fill in the format of the number of conversion, and then verify. The format takes the form of YYYY-MM-DD.

Original location:http://lxbzj.com/product/vform/index.htm , the original file applies a calendar input control here omitted ...

Total Code :

Run Code Box

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd "><ptml xmlns=" http://www.w3.org/1999/xhtml "><pead><meta http-equiv=" Content-type "content=" text/html; charset=gb2312 "/><title>vform form validator </title><style type=" Text/css "><!--div.info {width: 170px;overflow:visible;height:auto;font-size:small;position:absolute;background-color: #FFffdd; border:1px solid 000;filter:progid:dximagetransform.microsoft.shadow (color= #111111, direction=135,strength=3); Top:375px;padding: 5px;left:671px;} Div.info_title.err{padding:5px;height:50px;width:24em;position:absolute;background-color: #FFFFCC; left:196px; top:114px;font-size:small;opacity:0.5;border:1px double #333333; Filter:shadow (color= #000000, direction=135); Filter:progid:DXImageTransform.Microsoft.Shadow (color= #111111, direction=135,strength=5); #form1. text_input {border-top:1px solid #333333; border-right:1px solid #999999; Border-bottom:1px solid #ddd; border-left:1px solid #000000; info_title {color: #FF0000; background: #ACB9D1;} #form1 {position:static;left:581px;top:463px;border:1px solid #3300FF;p adding:5px;;} #imok {display:block;position:absolute;height:315px;overflow:scroll;left:100px;top:100px;width:306px;}. Title H1 {background: #33CCFF; border-bottom:medium solid #3366FF;}. Title p {font-size:medium;text-indent:2em;} Body {Font-family:verdana, Arial, Helvetica, Sans-serif;font-size:medium;} code {FONT:12PX/18PX "Lucida Grande", Verdana, Lucida, Arial, Helvetica, "Song Body", sans-serif;border:1px solid #0099cc;p addin G:5px;margin:5px;width:80%;color: #000; Background-color: #ddedfb;d isplay:block; --></style><script language= "JavaScript" type= "Text/javascript" >//program basic Ideas: By extending the object to implement the string extension Defines two custom objects for the default form element extension. string.isemail//string.isurl//form elements. required//form elements. isvalid//form elements. validate////string Validation Extension// ├ e-mail Authentication String.prototype.isEmail = function () {var tmpstr = This;var email =/^\w+ ([-+.]\w+) *@\w+ ([-.] \w+) *\.\w+ ([-.] \w+) *$/;return email.test (TMPSTR)}//├http address Validation String.prototype.isUrl = function () {var url =/^http:\/\/[a-za-z0-9]+\.[ a-za-z0-9]+[\/=\?%\ -&_~ ' @[\]\ ': +!] * ([^<>\ "\"]) *$/;var tmpstr = This;return url.test (TMPSTR); ├ Date Validation (Part I) String.prototype.isDateTime = function () {if (date.parse) | | Date.parsedate (this)) {return true;} Else{return false;}} String.prototype.isInteger = function () {var _i =/^[-\+]?\d+$/;var _s = this; return _i.test (_s);} Date.prototype.toIsoDate = function () {var _d = This;var _s;_y =_d.getfullyear (); _m = _d.getmonth () + 1;_d = _d.getdate (); _ H = _d.gethours (); _i = _d.getminutes (); _s = _d.getseconds (); with (_d) {_s = [getmonth () + 1,getdate (), getHours (), Getminutes (), getseconds ()];} for (var i = 0; i < _s.length i++) {if (_s[i].tostring (). length = = 1) _s[i]= ' 0 ' +_s[i];} Return (_y + '-' +_s[0]+ '-' +_s[1]+ ' +_s[2]+ ': ' +_s[3]+ ': ' +_s[4])}//├ Date validation (Part II) date.parsedate = function (str, FMT) {FMT = fmt| | " %y-%m-%d%h:%m "; var today = new Date (); var Y = 0;var m = -1;var D = 0;var a = Str.split (/\w+/); var b = Fmt.match (/%./g); var i = 0, j = 0;var hr = 0;var min = 0;for (i = 0; i < a.length; ++i) {if (!a[i]) Continue;switch (B[i]) {case '%d ': Case '%e ':d = parseint (A[i], ten); Case "%m": M = parseint (A[i], ten)-1;break; Case "%Y": Case "%Y": y = parseint (a[i],;(y <) && (y = = (Y >)? 1900:2000); Case "%b": Case "%b": for (j = 0; J < ++j) {if (calendar._mn[j].substr (0, A[i].length). toLowerCase () = = A[i].tolo Wercase ()) {m = J; break;}} Break Case "%H": Case "%I": Case "%k": Case "%l": hr = parseint (a[i), ten); Case "%P": Case "%P": if (/pm/i.test (a[i) && hr <) HR + + 12;else if (/am/i.test (a[i)) && HR >= HR-= 12;break; Case "%m": Min = parseint (A[i], ten); if (isNaN (y)) y = Today.getfullyear (), if (isNaN (m)) m = Today.getmonth (), if (isNaN (d)) d = today.getdate (); if (isNaN (HR)) hr = Today.gethours (); if (isNaN (min)) min = Today.getminutes () or if (Y!= 0 && m!=-1 && d!= 0) return new Date (Y, M, D, HR, Min, 0); y = 0; m =-1; D = 0;for (i = 0; i < a.length; ++i) {if (A[i].search (/[a-za-z]+/)!=-1) {var t = -1;for (j = 0; J <; ++j) {if ( Calendar._mn[j].substr (0, A[i].length). toLowerCase () = = A[i].tolowercase ()) {t = j; break;}} if (t!=-1) {if (M!=-1) {d = m+1;} m = t;} else if (parseint (A[i], ten) <= && m = = 1) {m = a[i]-1;} else if (parseint (A[i), ten) > && y = = 0 {y = parseint (A[i], ten);(y <) && (y = = (y > 29)? 1900:2000); else if (d = = 0) {d = a[i];}} if (y = = 0) y = today.getfullyear (); if (M!=-1 && d!= 0) return to new Date (Y, M, D, HR, Min, 0); return today;};/ /Extended completion//object definition var vform = new object;//Gets the display position of the pop-up prompt vform.getabsolutepos = function (EL) {var _p = {x:0, y:0}; do{_p.x + = (E L.offsetleft-el.scrollleft); _p.y + = (el.offsettop-el.scrolltop); while (el=el.offsetparent) return _p; };vform.tostring =function () {return ("vform form validator \ n version: 1.0beta\n author: Lei Xiaobao \ Time: 2006-07-31\n URL: http://lxbzj.com\n License: LGPL");} Vform.rules = new Array;vform.rules.add = function (obj,minlength,datatype,errmsg,maxlength,rule,patams) {var Curlen = t His.length; This[curlen] = [Obj,minlength,datatype,errmsg,maxlength,rule,patams]; This[curlen] = [0, 1, 2, 3, 4, 5, 6]; return this.length;} vform.init= function () {if (document.getElementById (this.form_id)) {//get form var o = document.getElementById (this.form_ ID);//Traversal rule for (var i = 0;i< this.rules.length;i++) {_r = this.rules[i]//add Validator if (_o = o.elements[_r[0]) {// Determine if required, whether there is a minimum length if (_r[1] > 0) {_o.required = true;//required meaning and minimum length of 1 is the same _o.minlength = parseint (_r[1));} else{_o.required = False;_o.minlength = 0;} Determine if there is a maximum length; if (_r[4]) {_o.maxlength = parseint (_r[4)); Add length validation functions _o.validlength = function () {var b =true;if (this.minlength) {b = (this.minlength <= this.value.length);} if (This.type = = ' textarea ' && This.maxLength) {b = b && (this.maxlength >= this.value.length);} return (b);} Add validation to format verify switch (_r[2]) {case ' e-mail ': _o.validate = function () {this.isvalid = This.validlength () && This.value.isEmail (); return (this.isvalid);}; Break;case ' url ': _o.validate = function () {if (this.value.substring (0,7)!= ' http://') this.value = ' http://' +this.value ; this.isvalid = This.validlength () && this.value.isUrl (); return (this.isvalid);} Break;case ' Date ': _o.validate = function () {var _d = date.parse (this.value) | | Date.parsedate (this.value); this.value = _d.toisodate (); this.isvalid = This.validlength () && This.value.isDateTime (); return (this.isvalid); a=a>b?1:1;} Break;case ' number ': _o.validate = function () {this.isvalid = This.validlength () && This.value.isInteger (); return (this.isvalid);} Break;case ' any ': _o.validate = function () {this.isvalid = This.validlength (); return This.isvalid}break;default:var RegExp =/^\\\w+$/;if (Regexp.test (_r[2]))//is required to be the same as the value of a field under the form. For heavyValidation of complex input {_el = _r[2].substring (1); if (O.elements[_el]) {_o.equal = _el;_o.validate = function () {if (_o = this.form.elements [This.equal]) {if (_o.value = this.value) && this.validlength ()) {return true;} else {return false;}} Else{alert (' Setup error ');}} Else{alert (_el + ' is not a valid form element '), _o.validate = function () {return true;}}} var regexp1 =/^\\ (==|! =|>=|<=|>|<)/;if (Regexp1.test (_r[2)) {_s0 = _r[2];_s1 = Regexp.$1;_s2 = _s0.replace (Regexp1, ' "); _ operator = _s1.substring (0);//comparison operator var regexp2 =/^\w+$/;if (Regexp2.test (_S2))//is an identifier, integer or variable {_o.operation = _ Operator+_s2;_o.validate = function () {_b = True;if (this.value.length!=0) {_b = eval (this.value+this.operation+ '; ');} _b = _b && this.validlength (); return _b;}}; break; Add validation hint (div tag) and initialize var _p = Vform.getabsolutepos (_o); _o.tip = new Tip (_r[3],vform.err_class,_p.x+_o.offsetwidth+3,_ P.Y); _o.tip.init (),//When the focus is lost, start validating _o.onblur =function (e) {if (This.minlength | | this.value.length >0) {if (This.validaTe ()) {this.tip.hide ();} Else{this.tip.show ()//Display error message//this.focus (); Add this sentence in IE will cause a dead loop:(return false;}}} Focus validation may fail, so final validation is required before the form is submitted as a final supplement. document.getElementById (this.form_id). onsubmit = function () {var valid = True;for (i=0;i<this.elements.length;i++) {_o = this.elements[i];if (_o.minlength &&!_o.isvalid) {_o.tip.show (); valid = false;}} return valid;}} Pop-up prompts define function tip (text,classname,x,y) {var o = document.createelement ("div"); o.style.display = "none"; o.innerhtml = Text;//var t = document.createtextnode (text);d ocument.body.appendChild (o);//o.appendchild (t); this.init = function ( dis) {o.classname = "info"; o.style.left = x+ "px"; o.style.top = y+ "px"; o.style.zindex = 100;if (dis) {o.style.display = "";} Else{o.style.display = "None";}} This.show = function () {o.style.display = "";} This.hide = function () {O.style.display = ' none ';}} function Start () {vform.form_id = ' Form1 ';//must be the form's Idvform.err_class = ' info ';//the style/validation rule for the error prompt, fill vform.rules.add (' Frm_name ', 1, ' e-mail ', ' please follow the user@domain.com formatEnter an e-mail address. &LT;BR/><span style= "color: #f00" > Required Items </span> ") vform.rules.add (' MyWeb ', 1, ' url ', ' please follow http:// Enter your URL in the www.domain.com format. &LT;BR/><span style= "color: #f00" > Required Items </span> ") vform.rules.add (' Dateinput ', 0, ' Date ', ' Please enter a date in the 2000-03-05 format. &LT;BR/><span style= "color: #f00" > Required Items </span> ") vform.rules.add (' QQ ', 0, ' number ', ' This must be an integer '); Vform.rules.add (' least10 ', ten, ' any ', ' you must fill in at least 10 <br/><span style= ' color: #f00 ' > Required Items </span> '); Vform.rules.add (' ok100 ', 1, ' Any ', ' is limited here to 100 characters <br/><span style= "color: #f00" > Required Items </span> ', 100); Vform.rules.add (' R_pass0 ', 5, ' any ', ' the shortest password 5-bit longest 20-bit <br/><span style= "color: #f00" > Required Items </span> ', 20); Vform.rules.add (' R_pass1 ', 5, "\\r_pass0", ' Confirm password error <br/><span style= ' color: #f00 ' > Required Items </span> ', 20) ; Vform.rules.add (' Frm_sel ', 1, "\\>2", ' must be greater than 2000<br/><span style= ' color: #f00 ' > Required Items </span> '); Vform.init ();} </script></pead><body ><form id= "Form1"Name=" Form1 "method=" Get "action=" ><label for= "Frm_name" >e-mail:<input name= "Frm_name" type= "text" class= "Text_input" id= "Frm_name" title= "Enter an e-mail address"/></label>*<p><label for= "R_pass0" > enter the password: <input name= "R_pass0" type= "text" class= "Text_input" id= "R_pass0" title= "Enter your desired password"/></label>*</p> <p><label for= "R_pass1" > Password confirmation: <input name= "R_pass1" type= "text" class= "Text_input" id= "R_pass1" title= "Confirm password Once"/></label>*</p><p><label for= "Frm_sel" > select: <select name= "Frm_sel" id= "Frm_" Sel "title=" Please select an answer "><option value=" 0 "> Please select an answer </option><option value=" 1 "selected=" selected "> 1000</option><option value= "2" >2000</option><option value= "3" >3000</option>< Option value= "4" >4000</option><option value= "5" >5000</option><option value= "6" >6000 </option></select></label>*</p><p><label for= "input3" > Input URL:<input name= "MyWeb" type= "text" class= "Text_input" id= "input3" title= "Enter a URL" onmousemove= "" value= "http://" Maxlength= "/></label>*</p><p><label" for= "dateinput" > Input date <input name= "Dateinput "Type=" text "class=" Text_input "title=" Enter a date "id=" Dateinput "/></label>*</p><p><label for= "Mub" > Input digital <input name= "QQ" type= "text" class= "text_input" title= "fill in the number" id= "Mub"/></label></p> <p><label for= "Len" > enter arbitrary but length limit to 10 <input name= "least10" type= "text" class= "Text_input" maxlength= "88" Id= "Len"/>*</label></p><p><label for= "text" > can only enter 100 <textarea name= "ok100" cols= "40" "Rows=" 5 "id=" text "title=" detailed content "></textarea>*</label></p><p><input type=" Submit " Name= "Submit" value= "Submission"/><button > About Validator </button></p></form><!--specific date settings, Must be placed in front of the body's end tag--><script type= "Text/javascript" >vform. Init (); Calendar.setup ({Inputfield : "Dateinput",//change this to the idifformat you need: "%y-%m-%d%h:%m",//format of the input fieldshowstime: True,//button: "Dateinput_btn", TimeFormat: "The"});</script><!--end specific date settings, must be placed in front of the body's closing tag-->& Lt;div class= "title" ><p>vForm1.0beta</p><ul><li> Author: Lei Xiaobao </li><li> Time:2006-08-08</li><li> URL:http://lxbzj.com</li><li>e-mail:lxbzmy@163.com</li>< Li> License:lgpl</li></ul><p> function brief:</p><ol> <li> <p> validation:</p> < Ul> <li>http address. </li> <li> Time Date </li> <li>e-mail</li> <li> digital </li> &LT;LI&G t; character length check </li> <li> one entry is compared with another input (for example: Confirm input for passwords) </li> <li> size comparison (only one comparison symbol) </li> &L T;/ul> </li> <li> <p> features </p> <ul> <li> extension easy and easy to add yourself need How to verify </li> <li> compatibility is good (ie5,6 firefox,oprea). </li> <li> availability is good, no alert () is used to eject the prompts;</li> </ul> </li> </ol><p> & Lt;/p><p> use method </p><p> use, you need to define a style of error prompt box, the style of this example is: <code>div.info {width:170px;<br/ > overflow:visible;<br/> height:auto;<br/> font-size:small;<br/> position:absolute;& Lt;br/> Background-color: #FFffdd; <br/> border:1px solid #000 <br/> Filter:progid:DXImageTrans Form. Microsoft.shadow (color= #111111 direction=135,strength=3) <br/> padding:5px;<br/>}</code></ P><p> then add <code><script type= "Text/javascript" src= "Calendar/calendar.js" in the Web page <pead> section > </script></code><br/>, then you can write a function to set the form name, verify the rule, <code>function start () <br/> {<br/&gt ; vformvform.form_id = ' Form1 '; <br/>vform.err_class = ' info '; <br/>//(Obj,required (True/false), DataType, ErrmsG,minlen,maxlen,rule,patams) <br/>//validation rules, fill <br/>vform.rules.add (' Frm_name ', 1, ' e-mail '), ' please follow Enter the e-mail address in the user@domain.com format. &LT;BR/><span style= "color: #f00" > Required Items </span> ") <br/>vform.rules.add (' MyWeb ', 1, ' url ', ' please follow Enter your URL in the http://www.domain.com format. &LT;BR/><span style= "color: #f00" > Required Items </span> ") <br/>vform.rules.add (' Dateinput ', 0, ' Date ', ' Please enter a date in the 2000-03-05 format. &LT;BR/><span style= "color: #f00" > Required Items </span> ") <br/>vform.rules.add (' QQ ', 0, ' number ', ' This must be an integer '); <br/>vform.rules.add (' least10 ', ' any ', ' you must fill in at least 10 <br/><span style= ' color: #f00 ' > Required </span> '); <br/>vform.rules.add (' ok100 ', 1, ' Any ', ' is limited to 100 characters <br/><span style= "color:# F00 "> Required Items </span>", <br/> Vform.init (); <br/>}</code> finally add the OnLoad event for body. <code> <body ></code></p><p> </p></div></body></ptml>

[Ctrl + A ALL SELECT hint: You can modify some of the code, and then run]



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.