JavaScript 策略模式封裝表單驗證庫

2021-08-11 21:33:50 字數 1966 閱讀 3304

直接上**:

html>

<htmllang=

"en">

<head>

<metacharset=

"utf-8">

<title>titletitle>

head>

<body>

<formid=

"form">

<p>使用者名稱:<inputtype=

"text"

name=

"username" />p>

<p>密碼:<inputtype=

"password"

name=

"userword"/>p>

<p>手機:<inputtype=

"tel"

name=

"userphone"/>p>

<p><inputtype=

"submit"

value="提交

">p>

form>

body>

<script>

varform= document.getelementbyid('form');

//定義驗證演算法類

varautoform=

},minlength :function(val,length,msg)

},isphone :function(val,msg) $)/.test( val ))

}

//這裡可以封裝無數個驗證演算法
};

varvalidator =function();

validator.prototype.add =function(dom,rule))

})(rule)}};

validator.prototype.start = function()}}

//定義執行演算法類

,並返回驗證結果

varvalidate =function(),]);

validator.add(form.userword,[,

]);validator.add(form.userphone,[,

]);varerrormsg = validator.start();

returnerrormsg;

};//

表單提交

form.onsubmit =function()else;

}script>

html>

javascript策略模式

var validator 驗證型別所對應的錯誤訊息 messages 當前需要使用的驗證型別 config 暴露的公開驗證型別 validate function data if type if checker result checker.validate data i if result re...

javascript設計模式 策略模式

1 var strategies 5 a function salary 8 910var getbonus function level,salary 1314 console.log getbonus s 10000 var strategies minlength function value...

JavaScript 模擬策略模式

模擬乙個介面,其方法會丟擲異常 function flyinter flyinter.prototype.fly function 實現乙個fly noway的方法 function flynoways flynoways.prototype.fly function 實現乙個fly with wi...