gpt4 book ai didi

javascript - 如何使用 knockout validation

转载 作者:行者123 更新时间:2023-12-03 11:17:29 24 4
gpt4 key购买 nike

我正在关注这个link创建验证。

但我不明白如何在我的代码中使用这个extend方法。

我将数据加载到我的可观察对象中,其中包含来自调用 Breeze 查询的记录。

我通过以下方式加载数据

dataObsArray= ko.observableArray()

datacontext.getData(id,dataObsArray)
.then(function () {

// some logic


})
.fail("Data not found");

然后我将此 obs 数组绑定(bind)到我的 View ,如下所示

<tbody data-bind="with: dataObsArraay">
<tr>
<td>name</td>
<td> <input data-bind=" value: Name" ></td>
<td> <input data-bind=" value: Age" ></td>

</tr>
</tbody>

所以我不明白如何使用extend方法,因为我只是使用将我的 View 与可观察数组中的属性绑定(bind)。

请指导我。

最佳答案

考虑使用breeze validation而不是通过 knockout 扩展器将验证逻辑放入 UI 代码中。使用 Breeze 验证将确保规则始终得到评估,并且使您无需为验证目的在实体上创建额外的模型。

这是一个使用 Breeze 内置验证器之一的示例:stringLength 验证器。

var entityType = entityManager.metadataStore.getEntityType('????'),
nameProperty = entityType.getProperty('Name'),
nameLengthValidator = breeze.Validator.stringLength({ maxLength: 10, minLength: 2 });
nameProperty.validators.push(nameLengthValidator);

下面是一个自定义必需的字符串验证器示例,该验证器不允许仅包含空格值:

// make a reusable validator
var myRequiredValidator = breeze.Validator.makeRegExpValidator(
"myRequiredValidator",
/\S/,
"The %displayName% '%value%' cannot be blank or entirely whitespace");

// register it with the breeze Validator class.
breeze.Validator.register(myRequiredValidator);

// add the validator to the Name property...
var entityType = entityManager.metadataStore.getEntityType('????'),
nameProperty = entityType.getProperty('Name');
nameProperty.validators.push(nameLengthValidator);

这是documentation用于制作正则表达式验证器。

您还可以编写自定义验证器 - 检查 breeze docs有关详细信息 - 请查找编写自定义验证器部分。

关于javascript - 如何使用 knockout validation ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27272656/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com