javascript - Backbone : my validation is not stopping white space being set to value

标签 javascript validation backbone.js backbone-views

我一直在关注 Backbone 上的教程,并在此处设置了我的任务项目:

http://leongaban.com/_pro/

现在在我的单个任务 View 中我有一个验证错误,我 found out here我需要{validation: true}

它的工作原理是它阻止用户输入空值(即:删除当前值)但是我不能阻止用户只输入空格

我的模型和验证方法:

App.Models.Task = Backbone.Model.extend({
    validate: function(attrs) {

        var errors = this.errors = {};

        if (attrs.title != null) {

            console.log('title is not null');

            if ($.trim(attrs.title) == null) {
                alert('error');
                console.log('title is required');
            }
        }

        // if ( $.trim(!attrs.title) ) {
        //  return false;
        // }
    }
});

这是您设置新值的地方:

editTask: function() {
        var newTaskTitle = prompt(this.msgPrompt, this.model.get('title'));

        // check for null value
        if ( !newTaskTitle ) return;

        console.log(newTaskTitle);
        this.model.set('title', newTaskTitle, { validate : true });
    },

If you notice in my example您可以更改该值并且它起作用,或者尝试删除并提交一个空值并且验证将停止它,但是如果用户只添加空格,您如何有效地不更改该值?

enter image description here

最佳答案

来自fine manual :

validate model.validate(attributes, options)

[...] If the attributes are valid, don't return anything from validate; if they are invalid, return an error of your choosing. It can be as simple as a string error message to be displayed, or a complete error object that describes the error programmatically.

您问题中的 validate 从不返回任何内容,因此它永远不会捕获无效值。

$.trim适用于字符串,而不是 bool 值,所以我不知道这是什么:

if ( $.trim(!attrs.title) ) {
  return false;
}

打算做的事。

如果您的验证看起来更像这样:

validate: function(attrs) {
    var errors = { };
    if('title' in attrs) {
        // Adjust this if you want to allow `null` values.
        if($.trim(attrs.title || '') === '') {
            errors.title = 'Missing title';
        }
    }
    return _(errors).isEmpty() ? undefined : errors;
}

那么也许你会得到更好的结果。

演示:http://jsfiddle.net/ambiguous/p9ah5/

一些注意事项:

  1. 我使用 in operator查看 attrs 是否有一个具有任何值的 'title' 键。该值可以是 nullfalse0'pancakes' 或...我们不关心值是什么,我们只关心它是否存在,所以我们使用 in 来准确表达我们的意思。
  2. 您似乎需要一个对象中的错误消息,所以我们填充一个对象并使用 _.isEmpty看看我们是否放了什么东西,然后我们就会知道我们应该返回什么。
  3. Backbone 会将错误放在 validationError 中所以不需要 this.error 东西。

关于javascript - Backbone : my validation is not stopping white space being set to value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20449832/

相关文章:

python - 使用 Python 和 lxml 针对外部 DTD 验证 XML

javascript - IE9 中的 Backbone 收集错误

javascript - 主干解析服务器对模型的响应

javascript - 属性错误 : 'WebDriver' object has no attribute 'manage' 的问题

javascript - 将 mysql 脚本转换为 sqlite 脚本

javascript - Java Script DOMException Web Audio API audioContext.createMediaElementSource 再次调用该函数

javascript - 主干忽略 idAttribute 并设置自己的

javascript - Jquery 与 Asp.net 按钮

ruby-on-rails - Rails ActiveRecord::RecordInvalid 异常未在关联的 after_create 中引发

mysql - 如何根据另一个表验证字段的唯一性