Javascript 淘汰验证和显示工具提示
我有一个带有knockout.validation的web应用程序示例。我需要显示所需属性的工具提示和消息-requiredText。我想在viewmodel中创建工具提示,而不是在html中,但我不能 HTML:Javascript 淘汰验证和显示工具提示,javascript,knockout.js,knockout-validation,Javascript,Knockout.js,Knockout Validation,我有一个带有knockout.validation的web应用程序示例。我需要显示所需属性的工具提示和消息-requiredText。我想在viewmodel中创建工具提示,而不是在html中,但我不能 HTML: <!DOCTYPE html> <html> <head> <title>ko.validation.test</title> <link href="Content/bootstrap.css" re
<!DOCTYPE html>
<html>
<head>
<title>ko.validation.test</title>
<link href="Content/bootstrap.css" rel="stylesheet" />
<link href="Content/bootstrap-theme.css" rel="stylesheet" />
</head>
<body>
<div class="container">
<h2>Required field validation</h2>
<div class="bs-docs-example">
<form>
<fieldset>
<div class="control-group" data-bind="validationElement: requiredText">
<label>Example 1 required</label>
<div class="input-append">
<input type="text" data-bind="value: requiredText" />
<button class="btn" data-bind="click: validateExample1Clicked">Validate</button>
</div>
<span class="label label-success" data-bind="visible: showExample1Success">Example 1 is valid</span>
<span class="label label-important" data-bind="visible: showExample1Failed">Example 1 is not valid</span>
<span class="help-inline" data-bind="validationMessage: requiredText"></span>
</div>
<div class="control-group" data-bind="validationElement: requiredTextUsingAttributes">
<label>Example 2 required attribute</label>
<div class="input-append">
<input type="text" data-bind="value: requiredTextUsingAttributes" required />
<button class="btn" data-bind="click: validateExample2Clicked">Validate</button>
</div>
<span class="label label-success" data-bind="visible: showExample2Success">Example 2 is valid</span>
<span class="label label-important" data-bind="visible: showExample2Failed">Example 2 is not valid</span>
<span class="help-inline" data-bind="validationMessage: requiredTextUsingAttributes"></span>
</div>
<div class="control-group">
<label>Optional</label>
<input type="text" data-bind="value: optionalText" />
</div>
<div class="form-actions">
<button class="btn btn-primary" data-bind="click: validateAllClicked">Validate all</button>
</div>
<div class="alert alert-error" data-bind="visible: showValidationErrors">
<strong>Not valid</strong> All the fields in the form are not valid.
</div>
<div class="alert alert-success" data-bind="visible: showValidationSuccess">
<strong>Valid</strong> All the fields are valid.
</div>
<div class="alert alert-info" data-bind="visible: errors().length > 0">
<strong>Form is not valid</strong> The form has following errors:
<ul data-bind="foreach: errors">
<li data-bind="text: $data"></li>
</ul>
</div>
</fieldset>
</form>
</div>
</div>
<script src="Scripts/jquery-2.1.1.js"></script>
<script src="Scripts/knockout-3.2.0.js"></script>
<script src="Scripts/knockout.validation.js"></script>
<script src="Scripts/bootstrap.js"></script>
<script src="ts/TestViewModel.js"></script>
</body>
</html>
验证试验
所需的字段验证
示例1要求
验证
示例1是有效的
示例1无效
示例2必需属性
验证
例2是有效的
示例2无效
可选择的
全部验证
无效表单中的所有字段均无效。
有效所有字段均有效。
表单无效表单存在以下错误:
JavaScript:
/// <reference path="../scripts/typings/knockout/knockout.d.ts" />
/// <reference path="../scripts/typings/knockout.validation/knockout.validation.d.ts" />
/// <reference path="../scripts/typings/bootstrap/bootstrap.d.ts" />
var TestViewModel = (function () {
function TestViewModel() {
var _this = this;
this.requiredText = ko.observable().extend({ required: true });
this.optionalText = ko.observable();
this.requiredTextUsingAttributes = ko.observable();
this.errors = ko.validation.group(this);
this.showValidationErrors = ko.observable(false);
this.showValidationSuccess = ko.observable(false);
this.showExample1Success = ko.observable(false);
this.showExample2Success = ko.observable(false);
this.showExample1Failed = ko.observable(false);
this.showExample2Failed = ko.observable(false);
this.validateExample1Clicked = function () {
if (!ko.validation.validateObservable(_this.requiredText)) {
alert("rrrrrr");
// Create tooltip
};
this.validateExample2Clicked = function () {
if (ko.validation.validateObservable(_this.requiredTextUsingAttributes)) {
_this.showExample2Success(true);
_this.showExample2Failed(false);
} else {
_this.showExample2Success(false);
_this.showExample2Failed(true);
}
};
this.validateAllClicked = function () {
if (_this.errors().length == 0) {
_this.showValidationSuccess(true);
_this.showValidationErrors(false);
} else {
_this.showValidationSuccess(false);
_this.showValidationErrors(true);
}
};
}
return TestViewModel;
})();
ko.validation.init({
parseInputAttributes: true,
decorateElement: true,
errorElementClass: 'error'
});
ko.applyBindings(new TestViewModel());
//# sourceMappingURL=TestViewModel.js.map
//
///
///
var TestViewModel=(函数(){
函数TestViewModel(){
var_this=这个;
this.requiredText=ko.observable().extend({required:true});
this.optionalText=ko.observable();
this.requiredTextUsingAttribute=ko.observable();
this.errors=ko.validation.group(this);
this.showValidationErrors=ko.可观察(假);
this.showValidationSuccess=ko.可观察(假);
this.showExample1Success=ko.可观察(假);
this.showExample2Success=ko.可观察(假);
this.showExample1Failed=ko.可观察(假);
this.showExample2Failed=ko.可观察(假);
this.validateExample1Clicked=函数(){
如果(!ko.validation.validateObservable(_this.requiredText)){
警报(“RRRR”);
//创建工具提示
};
this.validateExample2Clicked=函数(){
if(ko.validation.validateObservable(_this.requiredTextUsingAttributes)){
_此.showExample2Success(true);
_此.showExample2失败(错误);
}否则{
_此.showExample2Success(false);
_此.showExample2Failed(true);
}
};
this.validateAllClicked=函数(){
如果(_this.errors().length==0){
_此.showValidationSuccess(true);
_此。showValidationErrors(false);
}否则{
_此.showValidationSuccess(false);
_此为.showValidationErrors(true);
}
};
}
返回TestViewModel;
})();
ko.validation.init({
ParseInputAttribute:true,
装饰元素:是的,
errorElementClass:'错误'
});
applyBindings(新的TestViewModel());
//#sourceMappingURL=TestViewModel.js.map
您可以使用来实现此类验证。下面是一个使用淘汰文档中的扩展程序代码的示例实现,只需单击“运行代码片段”即可查看工作演示:
JS&HTML:
ko.extenders.required=函数(目标,覆盖消息){
//在我们的可观测数据中添加一些子可观测数据
target.hasError=ko.observable();
target.validationMessage=ko.observable();
//定义一个函数来进行验证
函数验证(newValue){
target.hasError(newValue?false:true);
target.validationMessage(newValue?“:overrideMessage | |“此字段为必填字段”);
}
//初步验证
验证(target());
//每当值更改时进行验证
目标。订阅(验证);
//返回原始的可观测值
回报目标;
};
函数TestViewModel(){
var self=这个;
self.name=ko.observable(“”).extend({required:“required”});
}
ko.applyBindings(新的TestViewModel());
姓名:
HTML:
身体{
字体系列:Helvetica、Arial、无衬线字体;
填充:10px;
}
字段集{
填充:10px;
边框:实心1px#ccc;
宽度:500px
}
标签{
显示:块;
宽度:100%;
填充:5px
}
.验证消息{
颜色:红色;
}
.警告{
边框颜色:红色;
}
.customMessage{
颜色:橙色;
}
输入{
边框:1px实心#ccc
}
所需的字段验证
提交
JavaScript:
ko.validation.rules.pattern.message='无效';
ko.validation.configure({
//decorateInputElement:true,
装饰元素:是的,
registerExtenders:对,
messages:false,
insertMessages:false,
ParseInputAttribute:true,
messageTemplate:null,
errorClass:“警告”
//没错
});
var ViewModel=函数(){
var self=这个;
self.lastName=ko.observable().extend({required:true});
self.isValidField=ko.observable();
this.submit=函数(){
if(self.errors().length==0){
警惕(‘谢谢’);
}否则{
self.errors.showAllMessages();
self.isValidField(self.lastName.isValid());
}
};
HTML:
<script src="Scripts/jquery-2.1.1.min.js"></script>
<script src="Scripts/knockout-3.2.0.js"></script>
<script src="Scripts/knockout.validation.js"></script>
<link href="Content/bootstrap.min.css" rel="stylesheet" />
<script src="Scripts/bootstrap.min.js"></script>
<script src="Scripts/ViewModel.js"></script>
<style>
body {
font-family: Helvetica, Arial, sans-serif;
padding: 10px;
}
fieldset {
padding: 10px;
border: solid 1px #ccc;
width: 500px
}
label {
display: block;
width: 100%;
padding: 5px
}
.validationMessage {
color: Red;
}
.Warning {
border-color: red;
}
.customMessage {
color: Orange;
}
input {
border:1px solid #ccc
}
</style>
<div id="contain" class="container">
<h2>Required field validation</h2>
<input data-bind="value: lastName, tooltip: isValidField" data-placement="below" data-title="Alert" data-content="We have identified this information is incorrect and must be updated." />
<button type="button" data-bind='click: submit'>Submit</button>
</div>
JavaScript:
ko.validation.rules.pattern.message = 'Invalid.';
ko.validation.configure({
//decorateInputElement: true,
decorateElement: true,
registerExtenders: true,
messagesOnModified: false,
insertMessages: false,
parseInputAttributes: true,
messageTemplate: null,
errorClass: 'Warning'
// errorAsTitle: true
});
var ViewModel = function () {
var self = this;
self.lastName = ko.observable().extend({ required: true });
self.isValidField = ko.observable();
this.submit = function () {
if (self.errors().length === 0) {
alert('Thank you.');
} else {
self.errors.showAllMessages();
self.isValidField(self.lastName.isValid());
}
};
self.errors = ko.validation.group(self);
};
ko.bindingHandlers.popover = {
init: function (element, valueAccessor, allBindingsAccessor) {
var value = valueAccessor(),
valueUnwrap = ko.unwrap(value),
allBindings = allBindingsAccessor(),
isValid = allBindings.value;
if (isValid) {
$(element).popover({
trigger: "hover"
});
} else {
$(element).popover("hide");
}
},
update: function (element, valueAccessor, allBindingsAccessor) {
var value = valueAccessor(),
valueUnwrap = ko.unwrap(value),
allBindings = allBindingsAccessor(),
isValid = allBindings.value;
if (isValid) {
$(element).popover({
trigger: "hover"
});
} else {
$(element).popover("hide");
}
}
};
ko.bindingHandlers.tooltip = {
init: function(element, valueAccessor) {
var local = ko.utils.unwrapObservable(valueAccessor()),
options = {};
ko.utils.extend(options, ko.bindingHandlers.tooltip.options);
ko.utils.extend(options, local);
$(element).tooltip(options);
ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
$(element).tooltip("destroy");
});
},
options: {
placement: "right",
trigger: "hover"
}
};
$(document).ready(function () {
ko.applyBindings(new ViewModel());
});
ko.validation.init{
insertMessages: false
}