2

I would like to be able to validate single fields at a time in my forms using backbone forms and backbone validation, however I am having problems getting this to work if I put my requirements in the model validation, rather than the schema.

My model is:

class Event extends Backbone.Model
  url: ->
    '/events' + (if @isNew() then '' else '/' + @id)

  validation:
    title:
      required: true
    start_date:
      required: true
    end_date:
      required: true

  schema: ->
    title:
      type: "Text"
    start_date:
      type: "DateTime"
      title: "Start Date"
      DateEditor: "DatePicker"
    end_date:
      type: "DateTime"
      title: "End Date"
      DateEditor: "DatePicker"

The code in my View that uses these is

class Events extends Backbone.View
  ...
  initialize: ->
    @form = new Backbone.Form(model: @model).render()
    Backbone.Validation.bind @form;

  validateField: (field) ->
    @form.on "#{field}:change", (form, fieldEditor) =>
      @form.fields[field].validate()

  render: ->
    ...
    @validateField for field of @form.fields
    ...

However, my problem is that it only seems to validate if I move the required: true into the schema like so:

schema: ->
  title:
    type: "Text"
    validators: ["required"]

However I'd rather not do this since, backbone.validation has a broader range of built-in validators which I would like to make use of outside this example.

I've noticed that backbone-forms states

There are 2 levels of validation: schema validators and the regular built-in Backbone model validation. Backbone Forms will run both when either form.commit() or form.validate() are called.

However I'm not sure it's running the regular validation when I validate the individual fields? The reasoning behind wanting to do this is that when a user starts creating an event I do not want to validate fields that they are yet to fill in.

Is there any way I can still validate individual fields without having to move the validation into the schema?

Thanks in advance.

======= UPDATE =======

On looking at the form editors source code for individual fields, the validate function is as so:

validate: function() {
  var $el = this.$el,
      error = null,
      value = this.getValue(),
      formValues = this.form ? this.form.getValue() : {},
      validators = this.validators,
      getValidator = Form.helpers.getValidator;

  if (validators) {
    //Run through validators until an error is found
    _.every(validators, function(validator) {
      error = getValidator(validator)(value, formValues);

      return error ? false : true;
    });
  }

  return error;
},

It does not appear to use the model validation, so I wonder how I can incorporate this?

Sarah Tattersall
  • 1,275
  • 2
  • 21
  • 32

0 Answers0