对于一个项目的表单验证,方式有很多,效果也有很多,具体使用哪种完成取决于产品这边,产品让你用什么,你就要用什么,而做为开发人员,我们要做的就是"整理近可能多的架构方式",这样才可以自由的应变.
对于表单验证,我今天看了新浪的邮箱注册,觉得效果还可以,所以,就写了一个,它利用了knockoutjs里的hasfocus属性,对文本框进行焦点捕捉来实现的.
新浪截图
说明:表单元素为焦点时,自动提示要输入的信息,当元素失去焦点时,提示用户输出的正确性,这个功能使用了hasfocus属性,下面看一下代码
HTML代码
<div class="editor-label"> 账号: </div> <div class="editor-field"> <input data-bind='value: name,validationElement:name,hasfocus:selName' /> <span class="validationWarn" data-bind="visible:selName">请输入用户名账号,它由字母汉字数字组成.</span> <span data-bind="visible:!selName()"><span class="validationError" data-bind="validationMessage:name"></span></span> <span data-bind="visible:!selName()"><span class="validationSuccess" data-bind="visible:name.isValid()"></span></span> </div> <div class="editor-label"> Email: </div> <div class="editor-field"> <input data-bind='value: Email,hasfocus:selEmail' /> <span data-bind="visible:!selEmail()"><span class="validationError" data-bind="validationMessage:Email"></span></span> <span class="validationWarn" data-bind="visible:selEmail">请输入你的Email.</span> <span data-bind="visible:!selEmail()"><span class="validationSuccess" data-bind="visible:Email.isValid()"></span></span> </div> <div class="editor-label"> 手机: </div> <div class="editor-field"> <input data-bind='value: phone,hasfocus:selPhone' /> <span data-bind="visible:!selPhone()"><span class="validationError" data-bind="validationMessage:phone"></span></span> <span class="validationWarn" data-bind="visible:selPhone">请输入你的电话.</span> <span data-bind="visible:!selPhone()"><span class="validationSuccess" data-bind="visible:phone.isValid()"></span></span> </div> <div style="clear: both;"></div> <p> <input type="button" value="Create" data-bind="click:Register" /> </p>
JS代码
var Product = function () { var self = this; ko.validation.configure({//ko.validation相关配置 insertMessages: false,//不自动插入错误消息 errorElementClass: 'errorElementClass',/*元素的CSS样式*/ errorMessageClass: 'errorMessageClass',/*提示信息CSS的样式*/ }); self.name = ko.observable().extend({ minLength: 2, maxLength: { params: 30, message: "名称最大长度为30个字符" }, required: { params: true, message: "请输入名称", } }); self.selName = ko.observable(false); self.phone = ko.observable().extend({ required: true, number: { params: true, message: "电话不合法", } }); self.selPhone = ko.observable(false); self.Email = ko.observable().extend({ required: { params: true, message: "请填写Email" }, email: { params: true, message: "Email格式不正确" } }); self.selEmail = ko.observable(false); self.Register = function () { self.errors = ko.validation.group(self); if (self.isValid()) { alert("验证成功,数据可以提交"); } else { self.errors.showAllMessages(); } }; }; product = new Product(); ko.applyBindings(product);
页面截图