使用Backbone验证表单

时间:2014-01-30 15:39:38

标签: javascript jquery validation backbone.js

如何验证从视图到模型的表单?

我只想检查电子邮件和密码是否包含至少6个字符。如果为true,则启用该按钮,否则抛出消息。

HTML

<form>
    <input type="text" name="email" placeholder="Type your email here." />
    <input type="password" name="password" placeholder="Type your password here." />
    <button disabled>Log In</button>
</form>

的JavaScript

var User = new Backbone.Model.extend({
});

var AppView = Backbone.View.extend({
    el: $('form'),
    events: {
        'keyup input[name=email]': 'validationScope'
    },
    initialize: function() {
        this.render();
    },
    validationScope: function() {
        console.log('testing');
        // What to do here?
    }
});

var appView = new AppView();

要玩,请执行right here

1 个答案:

答案 0 :(得分:2)

只需检查插补字符的长度是否为leas 6。

例如

validationScope: function(e) {
        console.log('testing');
        // What to do here?
        var email = e.currentTarget.value;

        this.$el.find('button').prop('disabled', !(email.length >= 6));

    }

或者在您的情况下,因为您希望电子邮件和密码至少包含6个字符

 events: {
        'keyup input[name=email]': 'validationScope',
        'keyup input[name=password]': 'validationScope'
    },
    initialize: function() {
        this.render();
    },
    validationScope: function() {
        console.log('testing');
        // What to do here?
        var email = this.$el.find('input[name=email]').val();
        var password = this.$el.find('input[name=password]').val();

        var disable = (email.length < 6 || password.length < 6);

        this.$el.find('button').prop('disabled',disable);

    }

以下是fiddle

的更新