EzDevInfo.com

backbone.validation

A validation plugin for Backbone.js that validates both your model as well as form input

Backbone.validation not working on save

I have a simple model using the Backbone.Validations plugin.

var LocationModel = Backbone.Model.extend({
validation: {
     location_name: {
         required   : true,
         msg        : 'A name is required for the location'
    }
} // end validation
});

var test = new LocationModel();
test.url = 'http://link-goes-here';
test.save();

It appears that on the save event, it's going ahead and saving my empty model even though the attribute "location_name" is required?


Source: (StackOverflow)

conditional validation with backbone.validation

i have a question regarding validation using backbone.validation

I have a group of fields that are required as a group, if one of the fields has value Meening if field A has a value field B and C are also required. and the other way around.

So if any of the fields in the group has a value, the other fields are required. But if none of the fields have a value none of the fields are required.

Currently I do this check on form submit, but I would also like to do in on the change input event. Any ideas on how to do this?


Source: (StackOverflow)

Advertisements

Backbone.js validation get list of properties from model for which the validation has failed

I want to get a list of all model's properties that have failed validation.

For example say my model is as the one below

var OfferModel = Backbone.Model.extend({
    , defaults: function () {
        return {
            Name: '',
            FunnyUrl: "",
            StartDate: "",
            EndDate: ""
        };
    }
    , validation: {
        Name: { required: true, msg: "Name is required." },
        FunnyUrl: [{ required: true, msg: "Funny Url is required." },
                   { pattern: 'url', msg: 'Enter valid URL, eg : http://yassershaikh.com'}],        
        StartDate: { required: true, fn: 'validateStartDate' },
        EndDate: { required: false, fn: 'validateEndDate' }
    }
});

My model contains too many properties I have kept only few to explain my problem better.

So say in my model if Name and FunnyUrl are not filled, I want a list of these properties name like

  • Name
  • FunnyList

I wanted the list of properties name that failed validation.

Please advice.


Source: (StackOverflow)

How to use Backbone.Validation plugin with Marionette.js

I am using Twitter Bootstrap3 with Backone.Validation(http://thedersen.com/projects/backbone-validation/) plugin in my Marionette.js app, but some how cannot get it right at all. can any one please give a simple example on how to use Backbone.Validation with Marionette.js (example similar to http://thedersen.com/projects/backbone-validation/#examples and _http://jsfiddle.net/thedersen/c3kK2/)

UPDATE: I have the following coding in place, I expected that the validation will be fired once the form is submitted, but unfortunately nothing is happening and there is not even an error. in my app.js (global)

//Backbone.Validation
Backbone.Validation.configure({
    forceUpdate: true
});

_.extend(Backbone.Validation.callbacks, {
    valid: function (view, attr, selector) {
        var $el = view.$('[name=' + attr + ']'),
            $group = $el.closest('.form-group');

        $group.removeClass('has-error');
        $group.find('.help-block').html('').addClass('hidden');
    },
    invalid: function (view, attr, error, selector) {
        var $el = view.$('[name=' + attr + ']'),
            $group = $el.closest('.form-group');

        $group.addClass('has-error');
        $group.find('.help-block').html(error).removeClass('hidden');
    }
});

My template looks like this:

<script id="signup-form" type='text/template'>
        <form class="form-signin control-group">
            <table>
                <tr><th><h2 class="form-signin-heading">Please sign up</h2></th></tr>
                <tr><td><input type="text" class="form-control" name="username" placeholder="Email address"></td></tr>
                <tr><td><input type="password" class="form-control" name="password" placeholder="Password"></td></tr>
                <tr><td><button class="btn btn-success form-control js-submit">Sign up</button></td></tr>
            </table>
        </form>

My model looks like this:

Entities.User = Backbone.Model.extend({
    urlRoot: "signup",

    defaults: {           

    },

    idAttribute: "_id",

    validation: {
        email: {
            required: true,
            pattern: 'email'
        },
        password: {
            minLength: 8
        }
    },
    validate:true
});

My view looks like this

Show.SignupPanel = Marionette.ItemView.extend({

    template: "#signup-form",


    events: {
        'click button.js-submit': 'signupClicked'
    },

    signupClicked: function (e) {
        //stop the default action of <a> tag and page refresh
        e.preventDefault();
        var data = Backbone.Syphon.serialize(this);
      if(this.model.isValid(true)) 
            this.trigger("form:submit", data);
    },

    initialize: function () {
        // This hooks up the validation
        // See: http://thedersen.com/projects/backbone-validation/#using-form-model-validation/validation-binding
        Backbone.Validation.bind(this);
    },

    remove: function () {
        // Remove the validation binding
        // See: http://thedersen.com/projects/backbone-validation/#using-form-model-validation/unbinding
        Backbone.Validation.unbind(this);
        return Backbone.View.prototype.remove.apply(this, arguments);
    }

});

Source: (StackOverflow)

Weird Backbone.Validation bug when used with require.js and backbone.stickit

I amusing T. Hedersen's backbone.validation plugin (https://github.com/thedersen/backbone.validation) in conjunction with backbone.stickit plugin for model binding. I am running into a weird error where in it constantly validates all the fields when a single attribute of the model changes. Here is the code

Model

define(function(require) {

    "use strict";
    var $ = require('jquery'),
            Backbone = require('backbone'),
            Validation = require('backbone.validation'),
            applicantModel = Backbone.Model.extend({
        defaults: {
            firstName: '',
            middleName: '',
            lastName: ''
        },
        initialize: function() {
        },
        validation: {
            firstName: {
                required: true
            },
             middleName: {
                required: true
            },
            lastName: {
                required: true
            }

        }
    });

    return new applicantModel;
});

View

define(function(require) {

"use strict";

var $ = require('jquery'),
        _ = require('underscore'),
        Backbone = require('backbone'),
        tpl = require('text!templates/primaryApplicantInfo.html'),
        lovValues = require('application/models/lovModel'),
        Stickit = require('stickit'),
        ApplicantModel = require('application/models/applicantModel'),
        Validation = require('backbone.validation'),
        template = _.template(tpl),

        applicantView = Backbone.View.extend({
         initialize: function() {
         console.log('Inside the initialization function');



        this.render();
    },
    bindings: {
        '[name=firstName]': {
            observe: 'firstName',
            setOptions: {
                validate: true
            }
        },
        '[name=middleName]': {
            observe: 'middleName',
            setOptions: {
                validate: true
            }
        },
        '[name=lastName]': {
            observe: 'lastName',
            setOptions: {
                validate: true
            }
        }
    },

    render: function() {
        console.log("Inside applicant view");
        //Render application header
        this.$el.html(template);
        this.stickit();
        Backbone.Validation.bind(this, {
        //The problem is here, this executes for all the attributes of the model when changing a single attribute
            forceUpdate: true,
            valid: function(view, attr) {
                console.log("Validity is proper for "+attr);
            },
            invalid: function(view, attr, error) {
                console.log("Validity is improper for "+attr);
            }
        });
        $.each(lovValues.toJSON().suffix, function(val, text) {
            console.log(text.text);
            $('#applicantInfoSuffix').append(new Option(text.text, text.value));
        });

Source: (StackOverflow)

Validation groups for Backbone.Validation

I have a Backbone model, say User, and I want to reuse it in a Sign Up page and in a Change settings page.. In the Sign Up page I have a form with two fields: email and password both required, while in the Change Settings page there is another form with email and name (but not the password field), the first required the second one not..

Using the Backbone.Validation plugin I have something like this for the validation process:

var User = Backbone.Model.extend({

  validation: {
    name: {
      rangeLength: [0, 100]
    }
    email: {
      required: true
      pattern: "email"
      rangeLength: [1, 100]
    }
    password: {
      required: true
      rangeLength: [8, 100]
    }
  } // validation

} // User

It works well for the Sign Up form, but it doesn't work in the Change Settings form since the password is missing.

Is there a way for reusing the same validation on two different forms as in my case? Something like validation groups, one group for sign up's fields and another one for settings's field (where I could exclude the password)?..


Source: (StackOverflow)

Detect Backbone model validation for any undesired attributes

I implemented this simple feature to detect any undesired or unspecified attributes in a Backbone Model:

var Underscore = require( '/usr/local/lib/node_modules/underscore' ),
    Backbone = require( '/usr/local/lib/node_modules/backbone' ),
    Validation = require( '/usr/local/lib/node_modules/backbone-validation' );

Underscore.extend( Backbone.Model.prototype, Validation.mixin );

var User = Backbone.Model.extend( {
   validation: {
        firstname: {
            minLength: 1,
            maxLength: 20,
            required: true
        },
        lastname: {
            minLength: 1,
            maxLength: 20,
            required: true
        }
    }, 
    ...

    isAttributeAccepted: function( attr ) {
        var retval = false;
        for ( var property in this.validation ) {
            if ( attr == property ) {
                retval = true;
                break;
            }
        }
        return retval;
    },
    ...

In use:

var user = new User();
var isDesired = user.isAttributeAccepted( "nop" );
console.log( isDesired ) // false;

I only done it because I cannot find anything in the Backbone.validation to replace this. How could I replace this code with a prefered way to use Backbone.validation (github thederson.com) ?

Thanks.


Source: (StackOverflow)

How to implement backbone.js validations/custom validations?

Need to validate one field based on the value of other field using backbone validation js. How to approach this ? Is it possible to validate using lib methods like range validator, max validator OR should I go with custom method ??

Normally this is how it looks,

bindings: {

    'value1': {

        Observe: 'value1',

        Setoptions:{

            Validate:true

        }

    }
}

This will call validate method

Validation: {

    Value1: {

        Pattern: number,

        Min: 0
        /* here we need to validate value1 < value2 where value 2 is value of another input field */

    }
}

Thanks


Source: (StackOverflow)

Backbone Validations on multiple fields of a model and returning same error

I have a model which has three fields field1, field2, field3. I have to validate that if any one of the three fields has some value then no error should be returned else an error should be returned.

My research: I can use Backbone.Validations plugin for this. as follows :

var model = Backbone.Model.extend({
  validation: {
    field1: {
        required: true,
        msg : "Field is required"
    }
    ,field2: {
        required: true,
        msg : "Field is required"
    }
    ,field3: {
        required: true,
        msg : "Field is required"
    }
  }
});

The above code will validate all three fields to be required.

I am clear until here. What i want is that if field1 is null, only then field2 is validated and similarly if field2 is null only then field3 is validated. And if field3 is also null, then an error message is returned. As soon as any of three fields is found to have a value the subsequent fields should not be validated.

I am not sure , if it possible to do such conditional validations using Backbone.Validations plugin. Please help, if this is possible. Also please suggest any links i may use to study Backbone more deeply as i am just a newbie to it.

I am following the following link for Backbone.Validation : https://github.com/thedersen/backbone.validation


Source: (StackOverflow)

Backbone Validation with complex objects

I'm having trouble getting Backbone.Validation to handle complex object validation. per the documentation:

Validating complex objects is also supported. To configure validation rules for objects, use dot notation in the name of the attribute, e.g 'address.street'.

I took the example fiddle and added a complex object but I can't get it to work.

var SignUpModel = Backbone.Model.extend({
    defaults: {
        terms: false,
        gender: '',
    },
    validation: {
        username: {
            required: true
        },
        email: {
            required: true,
            pattern: 'email'
        },

        // complex object
        'address.zip': {
            required: true
        },

It looks like the dot notation in the name on the input element because I'm getting this error:

Uncaught Error: Syntax error, unrecognized expression: [name=address.zip] 

Have a look at the fiddle here.


Source: (StackOverflow)

Backbone.Validation plugin - How to validate only the attributes that is set

How to validate just the one's that are set. Is there another method other than model.isValid(true) or model.validate() which would not validate the complete model. Here are some config that is there in my code

_.extend Backbone.Model.prototype, Backbone.Validation.mixin
Backbone.Validation.configure
        forceUpdate: true

setting one attribute with {validate:true} is triggering validate on the entire model

thanks


Source: (StackOverflow)