< html> < head> < meta http-equiv = " Content-Type;charset=utf-8" /> < title> 函数柯里化</ title> < style type = " text/css" > #user,#pwd { color : red; font-size : 14px; } </ style> </ head> < body> < form id = " form1" method = " post" action = " " > < input type = " text" name = " user" value = " " verify = " username|required" size = 20/> < span id = " user" > </ span> < br/> < input type = " password" name = " pwd" value = " " verify = " password|required" size = 20/> < span id = " pwd" > </ span> < br/> < input type = " button" name = " btn" value = " 提交" /> </ form> < script type = " text/javascript" > function form ( arr ) { var status= [ ] ; var verifylist= { digit : function ( val ) { return { msg : '非合法数字' , reg : / \d+ / } } , email : function ( val ) { return { msg : '非合法数字' , reg : / \d+ / } } , phone : function ( val ) { return { msg : '非合法电话' , reg : / ^1(3|4|5|6|7|8|9)\d{9$} / } } , required : function ( val ) { return { msg : '不为能空' , reg : / \S / } } } ; this . verify= arr; var form= document. forms[ 0 ] ; this . addVerify = function ( ) { this . verify. forEach ( function ( item, index, array ) { verifylist[ item. name] = item. verify; } ) ; } this . getverify = function ( ) { return verifylist} this . init = function ( ) { this . addVerify ( ) ; var that= this ; for ( const key of form. elements) { if ( key. name!= "btn" ) { key. onblur = function ( event ) { that. validation ( key) ; } ; status[ key] = false ; } } } ; this . validation = function ( key ) { var value= key. value; var rule= key. getAttribute ( 'verify' ) ; var rs= rule. split ( '|' ) ; var that= this ; rs. forEach ( function ( item, index, array ) { var x= that. getverify ( ) [ item] ; var reg= RegExp ( x ( ) . reg) ; let msgSpan= document. getElementById ( key. name) ; switch ( item) { case 'username' : if ( ! reg. test ( value) ) { msgSpan. innerHTML= x ( ) . msg; status[ key] = false ; } else { msgSpan. innerHTML= '' ; status[ key] = true ; } break ; case 'password' : if ( ! reg. test ( value) ) { msgSpan. innerHTML= x ( ) . msg; status[ key] = false ; } else { msgSpan. innerHTML= '' ; status[ key] = true ; } break ; case 'required' : if ( ! reg. test ( value) ) { msgSpan. innerHTML= x ( ) . msg; status[ key] = false ; } break ; } } ) ; } ; this . submitform = function ( ) { form. elements. btn. onclick = function ( ) { if ( Object. values ( status) [ 0 ] == true ) { form. submit ( ) ; alert ( '提交成功' ) ; } else { alert ( "表单不正确,提交失败" ) ; } } ; } ; } var ver= [ { name : 'username' , verify : function ( val ) { return { msg : '用户名为4-16位' , reg : / ^[a-z0-9_-]{4,16}$ / } } } , { name : 'password' , verify : function ( val ) { return { msg : '最少6位' , reg : / (\S+){6,}$ / } } } ] ; var f= new form ( ver) ; f. init ( ) ; f. submitform ( ) ; </ script> </ body>
</ html>