最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Backbone.js model with validation for creating user and logging in user - Stack Overflow

programmeradmin0浏览0评论

I have a model User. The model currently works with a Register view to 'register' a new user.

User:

var User = Backbone.Model.extend({
    url: '/user',
    defaults: {
        first_name: '',
        last_name: '',
        email: '',
        username: '',
        password: ''
    },
    parse: function(response){
        if(response.username) {
            this.trigger('username_check',response.username);
        }
        if(response.email) {
            this.trigger('email_check',response.email);
        }       
    },
    validate: function(attrs) {

        var email_filter    = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
        var username_filter = /^([a-zA-Z0-9]){0,1}([a-zA-Z0-9])+$/;

        errors = [];

        if (attrs.first_name == '') 
            errors.push({name: 'first_name', error: 'Please enter your First Name'});

        if (attrs.last_name == '') 
            errors.push({name: 'last_name', error: 'Please enter your Last Name'});

        if (!email_filter.test(attrs.email)) 
            errors.push({name: 'email', error: 'Please enter a valid email address'});

        if (!username_filter.test(attrs.username)) 
            errors.push({name: 'username', error: 'Your username contains invalid characters.  Usernames may only contain letters and numbers.'});          

        if (attrs.username == '') 
            errors.push({name: 'username', error: 'Please provide a valid username'});

        if (attrs.username.length > 12) 
            errors.push({name: 'username', error: 'Your username must be less than 12 characters'});    

        if (attrs.username.length < 4) 
            errors.push({name: 'username', error: 'Your username must be at least 4 characters'});

        if (attrs.password == '') 
            errors.push({name: 'password', error: 'Please provide a password.'});           

        if (attrs.password.length < 5) 
            errors.push({name: 'password', error: 'Your password must be at least 5 characters in length.'});

        if(errors.length > 0) 
           return errors;
        }
});

View:

    var Register = Backbone.View.extend({

        initialize: function() {

            this.user = new User;
            this.first_name             = this.$('input[name="first_name"]');
            this.last_name              = this.$('input[name="last_name"]');
            this.email                  = this.$('input[name="email"]');
            this.username               = this.$('input[name="username"]');
            this.password               = this.$('input[name="password"]');
            this.confirm_password       = this.$('input[name="confirm_password"]'); 
            this.redirect_url           = $(this.el).attr('data-redirect-url');

        },
        events: {
            'submit form' : 'onSubmit',
            'blur input[name="username"]' : 'checkUsernameExists',
            'blur input[name="email"]'    : 'checkEmailExists'
        },
        checkUsernameExists: function(e) {
            var self = this;
            if(this.username.val().length > 3) {
                this.user.fetch({data: {username : this.username.val(), check : 'true'}});
                this.user.on("username_check", function(status){
                    if(status == 'unavailable') {
                        self.processErrors([{name: 'username', error: 'This username is already taken, please try another.'}]);
                    } else {
                        $('input[name="username"]').closest('.controls').find('div.control-error').empty();
                    }
                })
            }
        },
        checkEmailExists: function(e) {
            var self = this;
            var email_filter    = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
            if (email_filter.test(this.email.val())) {
                this.user.fetch({data: {email : this.email.val(), check : 'true'}});
                this.user.on("email_check", function(status){
                    if(status == 'unavailable') {
                        self.processErrors([{name: 'email', error: 'This email is already used.  Please login to your account or use a different email.'}]);
                    } else {
                        $('input[name="email"]').closest('.controls').find('div.control-error').empty();
                    }
                })
            }
        },  
        onSubmit: function(e) {

            var self = this;
            e.preventDefault();

            var attrs = {
                'first_name': this.first_name.val(),
                'last_name':  this.last_name.val(),
                'email':    this.email.val(),
                'username': this.username.val(),
                'password': this.password.val()
            };

            $('div.control-error').html('');

            var user = this.user.set(attrs, {
                  error: function(model, response) {
                    self.processErrors(response);
                  }
            });

            if(user) {

                errors = [];

                if (self.confirm_password.val() == '') 
                    errors.push({name: 'confirm_password', error: 'Please confirm your password.'});

                else if (self.confirm_password.val() !== self.password.val()) 
                        errors.push({name: 'confirm_password', error: 'Your passwords do not match.  Please confirm your passwords.'});

                if(errors.length > 0) {
                    self.processErrors(errors);
                 } else {

                    user.save(this.attrs, {
                        success: function(model, response){
                        window.location.href = self.redirect_url;
                    }});
                }
            }

        },
        processErrors: function(response) {
            for (var key in response) {
                if (response.hasOwnProperty(key)) {
                    field = response[key];
                    $('input[name="'+field.name+'"]').closest('.controls').find('div.control-error').html(field.error);
                }
            }


}
});

Now I want to handle the Login view. Should I use the same model? Considering it validate methods that are irrelevant to the login view (Email/Pass).

Is there a best practice or remended way for handling this? I'm using backbone primarily for code separation - it's not an all ajax app, only the form handling is ajax, then it redirects to a new page upon success. The is the flow of the site.

Any suggestions/remendations would be great for how to handle validation and various interactions with a model like this, for Registering a user to Logging in a user.

I'm thinking of creating a new model UserLogin - but not sure if that would be best.

I have a model User. The model currently works with a Register view to 'register' a new user.

User:

var User = Backbone.Model.extend({
    url: '/user',
    defaults: {
        first_name: '',
        last_name: '',
        email: '',
        username: '',
        password: ''
    },
    parse: function(response){
        if(response.username) {
            this.trigger('username_check',response.username);
        }
        if(response.email) {
            this.trigger('email_check',response.email);
        }       
    },
    validate: function(attrs) {

        var email_filter    = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
        var username_filter = /^([a-zA-Z0-9]){0,1}([a-zA-Z0-9])+$/;

        errors = [];

        if (attrs.first_name == '') 
            errors.push({name: 'first_name', error: 'Please enter your First Name'});

        if (attrs.last_name == '') 
            errors.push({name: 'last_name', error: 'Please enter your Last Name'});

        if (!email_filter.test(attrs.email)) 
            errors.push({name: 'email', error: 'Please enter a valid email address'});

        if (!username_filter.test(attrs.username)) 
            errors.push({name: 'username', error: 'Your username contains invalid characters.  Usernames may only contain letters and numbers.'});          

        if (attrs.username == '') 
            errors.push({name: 'username', error: 'Please provide a valid username'});

        if (attrs.username.length > 12) 
            errors.push({name: 'username', error: 'Your username must be less than 12 characters'});    

        if (attrs.username.length < 4) 
            errors.push({name: 'username', error: 'Your username must be at least 4 characters'});

        if (attrs.password == '') 
            errors.push({name: 'password', error: 'Please provide a password.'});           

        if (attrs.password.length < 5) 
            errors.push({name: 'password', error: 'Your password must be at least 5 characters in length.'});

        if(errors.length > 0) 
           return errors;
        }
});

View:

    var Register = Backbone.View.extend({

        initialize: function() {

            this.user = new User;
            this.first_name             = this.$('input[name="first_name"]');
            this.last_name              = this.$('input[name="last_name"]');
            this.email                  = this.$('input[name="email"]');
            this.username               = this.$('input[name="username"]');
            this.password               = this.$('input[name="password"]');
            this.confirm_password       = this.$('input[name="confirm_password"]'); 
            this.redirect_url           = $(this.el).attr('data-redirect-url');

        },
        events: {
            'submit form' : 'onSubmit',
            'blur input[name="username"]' : 'checkUsernameExists',
            'blur input[name="email"]'    : 'checkEmailExists'
        },
        checkUsernameExists: function(e) {
            var self = this;
            if(this.username.val().length > 3) {
                this.user.fetch({data: {username : this.username.val(), check : 'true'}});
                this.user.on("username_check", function(status){
                    if(status == 'unavailable') {
                        self.processErrors([{name: 'username', error: 'This username is already taken, please try another.'}]);
                    } else {
                        $('input[name="username"]').closest('.controls').find('div.control-error').empty();
                    }
                })
            }
        },
        checkEmailExists: function(e) {
            var self = this;
            var email_filter    = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
            if (email_filter.test(this.email.val())) {
                this.user.fetch({data: {email : this.email.val(), check : 'true'}});
                this.user.on("email_check", function(status){
                    if(status == 'unavailable') {
                        self.processErrors([{name: 'email', error: 'This email is already used.  Please login to your account or use a different email.'}]);
                    } else {
                        $('input[name="email"]').closest('.controls').find('div.control-error').empty();
                    }
                })
            }
        },  
        onSubmit: function(e) {

            var self = this;
            e.preventDefault();

            var attrs = {
                'first_name': this.first_name.val(),
                'last_name':  this.last_name.val(),
                'email':    this.email.val(),
                'username': this.username.val(),
                'password': this.password.val()
            };

            $('div.control-error').html('');

            var user = this.user.set(attrs, {
                  error: function(model, response) {
                    self.processErrors(response);
                  }
            });

            if(user) {

                errors = [];

                if (self.confirm_password.val() == '') 
                    errors.push({name: 'confirm_password', error: 'Please confirm your password.'});

                else if (self.confirm_password.val() !== self.password.val()) 
                        errors.push({name: 'confirm_password', error: 'Your passwords do not match.  Please confirm your passwords.'});

                if(errors.length > 0) {
                    self.processErrors(errors);
                 } else {

                    user.save(this.attrs, {
                        success: function(model, response){
                        window.location.href = self.redirect_url;
                    }});
                }
            }

        },
        processErrors: function(response) {
            for (var key in response) {
                if (response.hasOwnProperty(key)) {
                    field = response[key];
                    $('input[name="'+field.name+'"]').closest('.controls').find('div.control-error').html(field.error);
                }
            }


}
});

Now I want to handle the Login view. Should I use the same model? Considering it validate methods that are irrelevant to the login view (Email/Pass).

Is there a best practice or remended way for handling this? I'm using backbone primarily for code separation - it's not an all ajax app, only the form handling is ajax, then it redirects to a new page upon success. The is the flow of the site.

Any suggestions/remendations would be great for how to handle validation and various interactions with a model like this, for Registering a user to Logging in a user.

I'm thinking of creating a new model UserLogin - but not sure if that would be best.

Share Improve this question asked Apr 6, 2012 at 17:13 dzmdzm 23.6k51 gold badges152 silver badges229 bronze badges 1
  • I think you had the right idea. One model for CRUD and another for login. – Gaston Sanchez Commented Sep 19, 2013 at 19:16
Add a ment  | 

1 Answer 1

Reset to default 5

You don't need a model for login. Have the view validate the form and just make a post request.

发布评论

评论列表(0)

  1. 暂无评论