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

我只想检查电子邮件和密码是否至少包含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

最佳答案

只需检查所推算字符的长度是否在第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的更新

09-25 16:46