JavaScript JSON data validation function

Source: Internet
Author: User
Tags eval tagname trim


This code can verify the mobile phone, mailbox, QQ, telephone, IP, data, Chinese characters, user name legality, mailbox, etc. oh.
var fk;
var mode;
validator={
Errinput: ' Errinput ',
ErrMsg: ' ErrMsg ',
ERRCLS: ' No ',
YESCLS: ' Yes ',

Require:/[^ (^s*) | ( s*$)]/,
Email:/^w+ ([-+.] w+) *@w+ ([-.] w+) *.w+ ([-.] w+) *$/,
Phone:/^ (((d{2,3)) | ( d{3}-))? ((0d{2,3}) |0d{2,3}-)? [1-9]d{6,7} (-d{1,4})? $/,
Mobile:/^ ((d{3}) | ( d{3}-))? 13[0-9]d{8}?$|15[0-9]d{8}?$/,
URL:/^http://[a-za-z0-9]+. [a-za-z0-9]+[/=?%-&_~ ' @[] ': +!] * ([^<> ""]) *$/,
Idcard: "This.isidcard (value)",
Currency:/^d+ (. d+)? $/,
Number:/^d+$/,
Zip:/^[1-9]d{5}$/,
IP:/^[d.] {7,15}$/,
QQ:/^[1-9]d{4,8}$/,
Integer:/^[-+]?d+$/,
Double:/^[-+]?d+ (. d+)? $/,
中文版:/^[a-za-z]+$/,
Chinese:/^[u0391-uffe5]+$/,
UserName:/^[a-z_]w{3,}$/i,
UnSafe:/^ ([a-z]*|[ a-z]*|d*| [-_~!@#$%^&*. () []{}<>?\/' "]*) |. {0,5}) $|s/,
UnSafe:/[<>?#$*&;\/[]{}= (). ^%,]/,
Safestr:/[^# ' "~.*$&;\/|] /,
Issafe:function (str) {return!this.unsafe.test (str);
Safestring: "This.issafe (value)",
Filter: "This.dofilter (value)",
Limit: "This.checklimit (Common.strlen (value))",
LIMITB: "This.checklimit" (this. LenB (value)) ",
Date: "This.isdate (value)",
Repeat: "This.checkrepeat (value)",
Range: "This.checkrange (value)",
Compare: "This.checkcompare (value)",
Custom: "This." Exec (value) ",
Group: "This.mustchecked ()",
Ajax: "This.doajax (Errindex)",

Isidcard:function (number) {
var date, Ai;
var verify = "10x98765432";
var Wi = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
var area = [', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ' Beijing ', ' Tianjin ', ' Hebei ', ' Shanxi ', ' Inner Mongolia ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ' , ', ', ', ' Shanghai ', ' Jiangsu ', ' Zhejiang ', ' Ann Micro ', ' Fujian ', ' Jiangxi ', ' Shandong ', ', ', ', ', ' Henan ', ' Hubei ', ' Hunan ', ' Guangdong ', ' Guangxi ', ' Hainan ', ', ', ', ', ' Chongqing ', ' Sichuan ', ' Guizhou ', ' Yunnan ', ' Tibet ', ', ', ', ', ', ', ', ', ', ', ', ', ' Shaanxi ', ' Gansu ', ' Qinghai ', ' Ningxia ', ' Xinjiang ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ' ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', '
var re = Number.match (/^ (d{2}) D{4} ((D{2) (d{2}) (D{2}) (D{3}) | ( (D{4}) (D{2}) (D{2}) (D{3}[xd])) $/i);
if (re = null) return false;
if (re[1] >= area.length | | area[re[1]] = = "") return false;
if (re[2].length = = 12) {
Ai = number.substr (0, 17);
Date = [Re[9], re[10], Re[11]].join ("-");
} else {
Ai = Number.substr (0, 6) + "n" + number.substr (6);
date = ["n" + re[4], re[5], Re[6]].join ("-");
}
if (!this.isdate (date, "Ymd")) return false;
var sum = 0;
for (var i = 0;i<=16;i++) {
Sum + + Ai.charat (i) * wi[i];
}
Ai + + Verify.charat (sum%11);

Return (number.length ==15 | | number.length = = && Number = Ai);
},

Isdate:function (OP) {
var formatstring = this[' element '].attr (' format ');
formatstring = formatstring | | "Ymd";
var m, year, month, day;
Switch (formatstring) {
Case "YMD":
m = Op.match (New RegExp (\d{4}) | ( \D{2})) ([-./]) (\d{1,2}) \4 (\d{1,2}) $));
if (M = = null) return false;
Day = m[6];
month = m[5]*1;
Year = (M[2].length = 4)? M[2]: getFullYear (parseint (m[3), 10));
Break
Case "DMY":
m = Op.match (New RegExp ("^ (\d{1,2}) ([-./]) (\d{1,2}) \2 ((\d{4}) | ( \D{2})));
if (M = = null) return false;
Day = m[1];
month = m[3]*1;
Year = (M[5].length = 4)? M[5]: getFullYear (parseint (m[6), 10));
Break
Default:
Break
}
if (!parseint (month)) return false;
month = Month==0 12:month;
var date = new Date (year, month-1, day);
return (typeof date = = "Object" && year = = Date.getfullyear () && month = = (Date.getmonth () +1) && Day = = Date.getdate ());
function getFullYear (y) {
Return (y<30? "A": "a") + y) |
}
},//end IsDate
Dofilter:function (value) {
var filter =this[' element '].attr (' accept ');
Return to New RegExp ("^.+." =ext) (EXT) $ ". Replace (/ext/g,filter.split (/s*,s*/). Join (" | "))," GI ". Test (value);
},

Checklimit:function (len) {
var minval=this[' element '].attr (' min ') | | Number.min_value;
var maxval=this[' element '].attr (' Max ') | | Number.MAX_VALUE;
Return (minval<= len && len<=maxval);

},

Lenb:function (str) {
Return Str.replace (/[^x00-xff]/g, "* *"). Length;
},

Checkrepeat:function (value) {
var to = this[' element '].attr (' to ');
Return Value==jquery (' input[name= "' +to+ '"]). EQ (0). Val ();
},

Checkrange:function (value) {
value = value|0;
var minval=this[' element '].attr (' min ') | | Number.min_value;
var maxval=this[' element '].attr (' Max ') | | Number.MAX_VALUE;
Return (Minval<=value && value<=maxval);
},

Checkcompare:function (value) {
var compare=this[' element '].attr (' compare ');
if (isNaN (value)) return false;
Value = parseint (value);
Return eval (value+compare);
},

Exec:function (value) {
var reg = this[' element '].attr (' regexp ');
Return to New RegExp (Reg, "GI"). Test (value);
},

Mustchecked:function () {
var tagname=this[' element '].attr (' name ');
var f=this[' element '].parents (' form ');
var n=f.find (' input[name= "' +tagname+ '"][checked] "). Length;
var count = f.find (' input[name= ' ' +tagname+ '] '). length;
var minval=this[' element '].attr (' min ') | | 1;
var maxval=this[' element '].attr (' Max ') | | Count
Return (minval<=n && n<=maxval);
},

Doajax:function (value) {
var fk;
var element = this[' element '];
var errindex = this[' Errindex '];
var url=this[' element '].attr (' url ');
var mode = element.attr (' mode ') | | 1;
var msgid = element.attr (' MsgId ');
var val = this[' element '].val ();
var str_errmsg=this[' element '].attr (' msg ');
var arr_errmsg = str_errmsg.indexof (' | ')? Str_errmsg.split (' | '): str_errmsg;
var errmsg = Arr_errmsg[errindex];
var type=this[' element '].attr (' type ');
var errcls=this[' Errcls '];
var yescls=this[' Yescls '];
var param = val this[' element '].attr (' param ') + ' &value= ' + val:this[' element '].attr (' param ');
var Charset = Browser.isie? Document.charset:document.characterSet;
var methodtype = (charset.tolowercase () = = ' Utf-8 ')? ' Post ': ' Get ';
var method=this[' element '].attr (' method ') | | Methodtype;
var s = $.ajax ({
Type:method,
Url:url,
Data:param,
Cache:false,
Async:false,
Success:function (data) {
data = Data.replace (/(^s*) | ( s*$)/g, "");
if (data!= ' success ')
{
ErrMsg = errmsg? Errmsg:data;
FK = false;
(type!= ' checkbox ' && type!= ' Radio ' && element.addclass (' errinput '));
if (mode = = 1)
{
if (MsgId)
{
id = ' # ' + msgid;
$ (ID). removeclass (' yes ');
$ (ID). addclass (' no ');
$ (ID). HTML (errmsg);
}
Else
{
JQuery ("<span tag= ' err ' class= '" +errcls+ "' ></span>"). HTML (errmsg). InsertAfter (Element);
}

}
else if (mode = = 2)
{
alert (errmsg);
}

       return false;
      }
       Else
       {
         FK = true;
        if (msgid)
      {
        id = ' # ' + msgid;
       $ (ID). removeclass (' no ');
       $ (ID). addclass (' yes ');
       $ (ID). HTML (');
      }
      else
      {

JQuery ("<span tag= ' err ' class= '" +yescls+ "' >&nbsp;</span>"). InsertAfter (Element);
}
return true;
}
}
}). responsetext;
s = S.replace (/(^s*) | ( s*$)/g, "");
return s = = ' success '? True:false;
}
};

Validator.showerr=function (element, Errindex) {
var str_errmsg=element.attr (' msg ') | | Unkonwn ';
var arr_errmsg = str_errmsg.split (' | ');
var errmsg = Arr_errmsg[errindex]? Arr_errmsg[errindex]: arr_errmsg[0];
var mode = element.attr (' mode ') | | 1;
var msgid= element.attr (' MsgId ');
var type=element.attr (' type ');
(type!= ' checkbox ' && type!= ' Radio ' && element.addclass (this[' errinput '));
if (mode = = 1)
{
if (MsgId)
{
id = ' # ' + msgid;
$ (ID). removeclass (' yes ');
$ (ID). addclass (' no ');
$ (ID). HTML (errmsg);
}
Else
{
JQuery ("<span tag= ' err ' class= '" "+this[' errcls ']+ '" ' ></span> "). HTML (errmsg). InsertAfter (Element);
}
}
Else
{
alert (errmsg);
}
}

Validator.removeerr = function (Element) {
Element.removeclass (this[' errinput '));
Element.parent (' * '). Find (' span[tag= "err"]). Remove ();
}

Validator.checkajax = function (element, datatype, Errindex)
{
var Value=jquery.trim (Element.val ());
this[' element ' = element;
this[' errindex '] = Errindex;
Validator.removeerr (Element);
Return eval (This[datatype]);
}

Validator.checkdatatype = function (Element,datatype) {
var Value=jquery.trim (Element.val ());
this[' element ' = element;
Validator.removeerr (Element);
Switch (datatype) {
Case "Idcard":
Case "Date":
Case "Repeat":
Case "Range":
Case "Compare":
Case "Custom":
Case "Group":
Case "Limit":
Case "LIMITB":
Case "safestring":
Case "Filter":
Return eval (This[datatype]);
Break

Default
return this[datatype].test (value);
Break
}
}

Validator.check=function (obj) {
var datatype = obj.attr (' datatype ');
if (typeof (datatype) = = "undefined") return true;

 if (obj.attr (' Require ')!= "true" && obj.val () = "") return true;
 var datatypes = datatype.split (' | ');
 var ok = true;

 jquery.each (Datatypes,function (index,data) {
  if (typeof (Validator[data)) = = "undefined") {
   ok = false;
   return  false;
  }
  if (Data!= ' Ajax ')
  {
   if (validator.checkdatatype (obj,data) = = False) {
    validator.showerr (obj, index);
    return Ok=false;
&NBSP;&NBSP;&NBSP}
   else
   {
    var msgid= Obj.attr (' MsgId ');
    if (msgid)
    {
     id = ' # ' + MsgId
     $ (ID). removeclass (' no ');
     $ (ID). addclass (' yes ');
     $ (ID). HTML (');
    }
    else
    {

JQuery ("<span tag= ' err ' class= ' yes ' ></span>"). InsertAfter (obj);
}
}
}
Else
{
OK = Validator.checkajax (obj, data, index);
}
});
return OK;
}

JQuery.fn.checkForm = function (m) {
mode = (m==1)? 1:0;
var form=jquery (this);
var elements = Form.find (' input[require],select[require],textarea[require] ');
Elements.blur (function (index) {
Return Validator.check (The JQuery (this));
});

 form.submit (function () {
  var ok = true;
  var errindex= New Array ();
 & Nbsp;var n=0;
  elements.each (function (i) {
   if (Validator.check (The JQuery (this)) ==false) {
    ok = false;
    errIndex[n++]=i;
   };
  });

  if (ok==false) {
   elements.eq (errindex[0)). focus (). Select ();
    return false;
  }
  if (document.getElementById (' Video_uploader ') &&!uploading)
  {
    uploadfile ();
   return false;
  }
  if ($ (' #f_filed_1 ') && set_show==false)
  {
   $ ("select[@ Id=catids] Option ". each (function ()
   {
    $ (this). attr (' selected ', ' Selected ');
   });
  }
  if ($ (' #hava_checked '). Val () ==0)
  {
   yp_checkform ()
   return false;
  }
  return true;
 });
}

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.