前端表单在提交前总是要进行校验的, 而这些工作是繁琐的, 所以这儿写了一个简单的校验框架, 代码实现如下:
- function Validate(id){
- if(arguments.length != 1){
- throw new Error("Argument is required");
- }
- this.errors = [];
- this.id = id;
- this.container = $("#" + id);
- }
- Validate.prototype = {
- constructor : Validate,
- rules : [
- "required"
- ],
- rulesCallback : {
- messages : {
- required: 'The %s field is required.'
- },
- required : function(control){
- var value = control.value;
- if ((control.type === "checkbox") || (control.type === "radio")) {
- var controls = $("input[name='" + control.name + "']");
- for(var i=0; i<controls.length; i++){
- if(controls[i].checked === true){
- return "";
- }
- }
- }
- else if(value && value.length> 0){
- return "";
- }
- return this.messages.required.replace("%s", control.name);
- }
- },
- validate : function(){
- this.errors.clear();
- var controls = this.container.find(".validate");
- if(controls != null){
- for(var i=0; i<controls.length; i++){
- for(var j=0; j<this.rules.length; j++){
- if(controls.hasClass(this.rules[j])){
- var error = this.rulesCallback[this.rules[j]](controls[i]);
- if(error.length> 0){
- this.errors.push(error);
- }
- }
- }
- }
- }
- return this.errors.length == 0 ? true:false;
- }
- }
- View Code
现在这儿只是实现了 required 的校验, 如果要添加其他校验可以按照如下步骤
- rules : [
- "required"
- ],
- rulesCallback : {
- messages : {
- required: 'The %s field is required.'
- },
- required : function(control){
- var value = control.value;
- if ((control.type === "checkbox") || (control.type === "radio")) {
- var controls = $("input[name='" + control.name + "']");
- for(var i=0; i<controls.length; i++){
- if(controls[i].checked === true){
- return "";
- }
- }
- }
- else if(value && value.length> 0){
- return "";
- }
- return this.messages.required.replace("%s", control.name);
- }
- },
1. 首先在 rules 中添加校验的类型;
2. 在 rulesCallback 的 message 中添加校验错误时的提示文本, 其中 %s 是占位符, 会使用表单元素的 name 值来替换. 提示文本的名字要和校验类型相同;
3. 在 rulesCallback 中添加一个和校验类型相同的方法, 并在方法中完成对某一控件的校验实现;
通过以上步骤就添加好了校验规则, 然后看一下使用, 代码如下:
- <!DOCTYPE>
- <html>
- <head>
- <title>demo</title>
- </head>
- <body>
- <div id="form">
- alias<input class="validate required" name="alias" type="text"/><br/>
- Content<input class="validate required" name="content" type="text" /><br/>
- public<input class="validate required" name="publiz" type="radio" />Private
- <input class="validate required" name="publiz" type="radio" />Public<br/>
- <button id="btnOK">OK</button>
- </div>
- <script src="jquery-3.2.1.js"></script>
- <script src="validate.js"></script>
- <script>
- $(function(){
- var val = new Validate("form");
- $("#btnOK").click(function(){
- val.validate();
- alert(val.errors);
- });
- });
- </script>
- </body>
- </html>
因为该框架实在 jquery 下工作的, 所以先要导入 jquery 库, 然后根据包含表单控件的元素的 id 属性来创建一个校验对象, 这样就可以在后面使用, 如上在点击 ok 按钮后开始进行校验, 通过 val.valdate() 方法返回是否是 false, 就可以知道是否有表单元素的值不合法, 如果有不合法的可以通过 val.errors 来获得提示语句.
其他规则的校验会在后面添加.
来源: http://www.bubuko.com/infodetail-2755820.html