question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Validation Behaviour & Guidelines (3.0) (question)

See original GitHub issue

From my understanding the default behavior of JS-Data is to validate on set. This is unusual and if possible it would be great to have some guidelines for how this should be applied (and the use cases for it - documentation on validation (3.0) is also missing at the moment).

Toy schema for reference <span id="a1">below</span>. Suppose as below I have defined minLength and maxLength on firstName now if the name is being sourced from user input directly something like person.firstName = 'j' will raise an error - is this tangibly useful? Is there an example somewhere of JS-Data glueing to input elements / error message handling ?

The possible use case I see is that the input element code would have to specify a try .. catch in it’s setter (and display a form / input as invalid until the property has been successfully set on the object), in which case the firstName would not be written to the model until it could validate min/max length.

Also there is a particularity to how this set behaviour will work when using nested fields (nice up-side to jsonschema though that they can be validated). So emergencyContact below allows ‘null’ so that it may be unset, but then expects to be filled in with required fields. That means that an input which attempts to set a valid contactNumber on the person instance will fail - and the entire form needs to be synced at once.

The later might look like this –

try {
  person.emergencyContact = this.emergencyContact
} catch(e) {
  e.errors.forEach((error) => {
    this.$[error.path.split('.')[1]] && (this.$[error.path.split('.')[1]].invalid = true);
  })
  return
}

but being explicit in each field set is probably less appealing than validate() - since the later could work generically and not need to be duplicated:

save(person) { 
  try { 
    person.validate() 
  } catch(e) {
    e.errors.forEach((error) => {
      this.$[error.path.split('.')[1]] && (this.$[error.path.split('.')[1]].invalid = true);
    })
    return 
  }
  person.save()
}

An interesting point @jmdobry brought up on slack was the use of a viewModel - in case of the later you could consider an interface that looks something like:

class Ephemeral {
  constructor(obj) {
    /*  Wraps a JS-Data model and proxies it's properties */
  }
  sync() {
    /* syncs proxied properties to underlying JS-Data model */ 
  }
}

I am inclined to think that in such a case the validation behaviour would like highly similar to the try .. validate() catch {..} save() though only it would be try .. sync() catch {..} save(). Not sure over-all how many advantages there are to separating view and data-models, but I suppose a lot of the ‘heaviness’ (e.g. changeTracking per set rather than per ‘persist’) comes from the JS-Data models being used on the back-end as well?

  const EmergencyContactSchema = new Schema({
   'properties': {
      'contactName': {'type': 'string'},
      'contactNumber': {'type': 'string'},
      'relationship': {'type': 'string'}
    },
    'required': ['contactName','contactNumber','relationship'],
    'type': ['object', 'null']
  })

  const PersonSchema = new Schema({
    $schema: 'http://json-schema.org/draft-04/schema#',
    title: 'Person',
    description: 'Schema for a Person Record.',
    type: 'object',
    properties: {
      firstName: { type: 'string', default: '', minLength: 2, maxLength: 32 },
      lastName: { type: 'string', default: '' },
      emergencyContact: EmergencyContactSchema,
    }
  })

  const Person = store.defineMapper('person', {
    endpoint: 'person/',
    schema: PersonSchema
  })

Issue Analytics

  • State:closed
  • Created 7 years ago
  • Comments:9 (7 by maintainers)

github_iconTop GitHub Comments

1reaction
jmdobrycommented, Feb 20, 2017

The configuration option was implemented a while back, here’s how it works:

// LOTS OF VALIDATION
store.defineMapper('user', {
  schema: {
    properties: {
      age: { type: 'number' }
    }
  }
});

// NO VALIDATION ON PROPERTY SETTERS
store.defineMapper('post', {
  // Disable validation on property setters
  validateOnSet: false,
  schema: {
    properties: {
      title: { type: 'string' }
    }
  }
});

// NO VALIDATION AT ALL
store.defineMapper('comment', {
  // Disable validation on property setters
  validateOnSet: false,
  // Skip validation in createRecord, beforeCreate, beforeCreateMany, etc.
  noValidate: true,
  schema: {
    properties: {
      content: { type: 'string' }
    }
  }
});
store.createRecord('user', { age: 'bar' }); // error is thrown

const user = store.createRecord('user', { age: 30 });
user.age = 'foo'; // error is thrown

store.createRecord('post', { title: 123 }); // error is thrown

const post = store.createRecord('post', { title: 'test' }); // error is NOT thrown
post.title = 1234; // error is NOT thrown

const comment = store.createRecord('comment', { content: 123 }); // error is NOT thrown
comment.content = 1234; // error is NOT thrown
0reactions
jmdobrycommented, Feb 20, 2017

I’ve also written http://www.js-data.io/v3.0/docs/validation. If you have further suggestions for that page (which still has some TODOs), please click the “Suggest Edits” button on the top right corner of that page.

Read more comments on GitHub >

github_iconTop Results From Across the Web

1EdTech Question & Test Interoperability (QTI) Specification
A QTI Conformance Certification program and online validation tool are available for 1EdTech members to test their assessment products against the QTI ...
Read more >
SEER ICD-O-3 Coding Materials
Access to Guidelines for ICD-O-3 Histology Code and Behavior (cases 1/1/18 and later) and ICD-O-3 SEER Site/Histology Validation List in PDF or Excel....
Read more >
Guidelines for developing, translating, and validating a ... - NCBI
A validated questionnaire refers to a questionnaire/scale that has been developed to be administered among the intended respondents.
Read more >
Best Practices for Developing and Validating Scales for Health ...
Scale development and validation are critical to much of the work in the health, social, and behavioral sciences.
Read more >
MDS 3.0 Validation Minimum Review Standards - Maryland.gov
Does require: • Example(s) of the resident's verbal and non-verbal ability and degree of impairment to express or communicate requests, needs, opinions, ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found