GithubHelp home page GithubHelp logo

xpepermint / vue-rawmodel Goto Github PK

View Code? Open in Web Editor NEW
81.0 4.0 7.0 1.39 MB

RawModel.js plugin for Vue.js v2. Form validation has never been easier!

JavaScript 17.23% Vue 30.94% TypeScript 51.83%
vue rawmodel model schema form validation reactivity debounce promise plugin

vue-rawmodel's Introduction

NPM Versionย Dependency Status

RawModel.js plugin for Vue.js v2. Form validation has never been easier!

This plugin integrates RawModel.js framework into your Vue.js application.

RawModel.js is a simple framework which provides a strongly-typed JavaScript object with support for validation and error handling. It has a rich API which significantly simplifies server-side and client-side data validation and manipulation. Because it's an unopinionated framework it flawlessly integrates with popular modules like vuex, apollo-client and other related libraries.

RawModel.js together with Vue.js represents a web framework on steroids. Thanks to its powerful and flexible model objects, a form validation has never been easier. This plugin brings even more elegant way to do form validation using RawModel.js and still leaves you freedom to customize and fine-tune the integration.

Make sure you check RawModel.js API page for details about the framework.

This is a light weight open source package for Vue.js written with TypeScript. It's actively maintained and ready for production environments. The source code is available on GitHub where you can also find our issue tracker.

Related Projects

  • RawModel.js: Strongly-typed JavaScript object with support for validation and error handling.

Installation

Run the command below to install the package.

$ npm install --save vue-rawmodel rawmodel

This package uses promises thus you need to use Promise polyfill when promises are not supported.

When used with a module system, you must explicitly install vue-rawmodel via Vue.use().

import Vue from 'vue';
import VueRawModel from 'vue-rawmodel';

Vue.use(VueRawModel);

Getting Started

This package provides a special class called ReactiveModel which extends from Model class provided by RawModel.js. You don't need to attach the plugin to Vue. ReactiveModel is completely independent thus you can use it directly. Below is an example of a simple reactive model called User with a single field name.

import {ReactiveModel} from 'vue-rawmodel';

class User extends ReactiveModel {
  constructor (data = {}) {
    super(data); // initializing parent class

    this.defineField('name', { // defining class property `name`
      type: 'String', // setting type casting
      validate: [ // field validations
        { // validator recipe
          validator: 'presence', // validator name
          message: 'is required' // validator error message
        }
      ]
      // check the API for all available options
    });
  }
}

We can optionally pass models to the root Vue instance as the models option. This will populate the $models property which is then injected into every child component.

const app = new Vue({
  models: { User }, // [optional] injecting models into child components (later available as this.$models.User)
  ...
});

Form Example

Object validation has been one of the incentives for creating RawModel.js framework. This plugin brings even more elegant way to do form validation.

<template>
  <form novalidate v-on:submit.prevent="submit">
    <!-- input field -->
    <input type="text" v-model="user.name" placeholder="User name"/>
    <span v-if="user.getField('name').hasErrors()">
      {{ user.getField('name').errors | firstMessage }}
    </span>
    <!-- buttons -->
    <button v-bind:disabled="user.hasErrors()">Submit</button>
  </form>
</template>

<script>
export default {
  data () {
    return {
      user: new this.$models.User({
        vm: this, // instance of Vue's VM
        dataKey: 'user', // name of data model key
        name: 'John Smith' // initializing the `name` field
      })
    };
  },
  methods: {
    submit () {
      // Send data to the remote server
    }
  }
}
</script>

Use the $populate() method to reactively apply data to your model.

export default {
  ...
  created () {
    this.user.$populate({
      name: 'John Smith'
    });
  }
}

Use Vue watchers to install real-time form validation.

export default {
  ...
  watch: {
    user: {
      handler: (user) => user.$validate({debounce: 300}), // reactively validate fields and display errors
      deep: true, // always required
      immediate: true // set this to validate immediately after the form is created
    }
  }
}

Check the RawModel.js API page and this package API section for details.

API

This plugin extends RawModel.js functionality, which help us write reactive code in Vue. If you don't need reactivity then you can use RawModel.js directly.

ReactiveModel

ReactiveModel({vm, dataKey, parent, ...data})

Abstract reactive class which represents a strongly-typed JavaScript object. This class extends from Model and adds new reactive capabilities.

Option Type Required Default Description
vm Vue No - Vue VM instance.
dataKey String No - The name of the data key.
parent Model No - Parent model instance.
data Object No - Data for populating model fields.

ReactiveModel.prototype.$applyErrors(errors): ReactiveModel

A reactive alternative of method applyErrors() which deeply populates fields with the provided errors (useful for loading validation errors received from the server).

Option Type Required Default Description
errors Array No [] An array of errors.

ReactiveModel.prototype.$clear(): ReactiveModel

Reactive alternative of method clear() which sets all fileds to null.

ReactiveModel.prototype.$fake(): ReactiveModel

Reactive alternative of method fake() which resets fields then sets fields to their fake values.

ReactiveModel.prototype.$forceUpdate (): ReactiveModel

Force the vm instance to re-render.

ReactiveModel.prototype.$handle (error, {quiet, debounce}): Promise

Reactive alternative of method handle() which handles the error and throws an error if the error can not be handled.

Option Type Required Default Description
error Any Yes - Error to be handled.
quiet Boolean No true When set to false, a handled validation error is thrown. This doesn't affect the unhandled errors (they are always thrown).
debounce Boolean 0 - Number of milliseconds to wait before running validations.

ReactiveModel.prototype.$invalidate (): ReactiveModel

Reactive alternative of method invalidate() which removes fields errors.

ReactiveModel.prototype.isReactive (): Boolean

Returns true when reactive properties (vm and dataKey) are set.

ReactiveModel.prototype.$populate (data): ReactiveModel

Reactive alternative of method populate() which applies data to a model.

Option Type Required Default Description
data Object Yes - Data object.

ReactiveModel.prototype.$rebuild (): ReactiveModel

Rebuilds model's reactivity system.

ReactiveModel.prototype.$reset (): ReactiveModel

Reactive alternative of method reset() which sets each model field to its default value.

ReactiveModel.prototype.$rollback (): ReactiveModel

Reactive alternative of method rollback() which sets each field to its initial value (value before last commit).

ReactiveModel.prototype.$validate({quiet, debounce}): Promise(ReactiveModel)

Reactive alternative of method validate() which validates the model fields and throws a validation error if not all fields are valid unless the quiet is set to true.

Option Type Required Default Description
quiet Boolean No true When set to true, a validation error is thrown.
debounce Boolean 0 - Number of milliseconds to wait before running validations.

Filters

firstMessage

Extracts the first error message from a list of errors.

Example

An example is available in the ./example folder which you can run with the npm run example command. There is also vue-example app available which you should take a look.

Tutorials

See vue-js-cheatsheet for more.

License (MIT)

Copyright (c) 2016 Kristijan Sedlak <[email protected]>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

vue-rawmodel's People

Contributors

xpepermint avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

vue-rawmodel's Issues

Example on loading data into model

Hi,

vue-contextable looks interesting - is it possible to get some guidance on best practice for loading/populating data into a model (e.g. json object returned from a get call to a web api). There appears to be a function 'populate(data)' defined for the document object in the objectschema package which may work but it does not seem to be available via this.{datakey}.$populate().

Any pointers would be appreciated.

Thanks,

Michael

Any way to check if the field is dirty?

For example, create a new form with two field, username and password, both are required. To prevent immediate showing of error, the vue watch has set immediate:false. But when the user start typing
username, the password field would render error. It would be useful if there is something like user.getField('username').isDirty().

    <div>
      <input type="text" v-model="username" />
      <span v-if="user.getField('username').hasErrors()">
        {{ user.getField('username').errors | firstMessage }}
      </span>
    </div>
    <div>
      <input type="text" v-model="password" />
      <span v-if="user.getField('password').hasErrors()">
        {{ user.getField('password').errors | firstMessage }}
      </span>
    </div>

How to set up a date field properly?

I've tried to setup a date field, but the v-model seems to give me trouble. With following code, I simply cannot type anything to the text input.

<template>
  <div>
    <input type="text" v-model="user.startDate"/>
    <pre>{{ userData }}</pre>
  </div>
</template>

<script>
  import {ReactiveModel} from 'vue-rawmodel';
  
  class User extends ReactiveModel{
    constructor(data = {}){
      super(data);
      this.defineField('startDate', {
        type: 'Date'
      });
      this.populate(data);
    }
  }
  
  export default {
    data(){
      return {
        user : new User({
          vm: this,
          dataKey: 'user'
        })
      }
    },
    computed:{
      userData(){
        return this.user.serialize();
      }
    },
    watch:{
      user:{
        handler: user => user.$validate(),
        deep: true,
        immediate: true
      }
    }
  }
  
</script>

example link: https://www.webpackbin.com/bins/-KmkBG8Nku2cQp0DVO_m

Required if validator

One of the validators that I will need for my project is for a field to be required (non-blank) only when a condition is met based on the value of one or more other fields in the model. Currently, it does not appear that any of the built-in validators that will handle such a scenario - none appear to use values of another field as part of the validation. I intend to look at the code more closely to try to work out how to implement this but first I would like to check that it should be relatively simple to do this with the package. Another validator of interest is to validate that the value of the field is less/greater/equal to another field (e.g. dates).

Any insight into this would be appreciated.

Shared client and server side validation models

Thank you so much for sharing this great library!

Is it possible to share models between client and server? I'm working on a vue front end with a feathers/express back end where I want to have a single source of validation. In order to share models, should I just make a models folder in the project root directory (along side app and src directories which contain vue and feathers apps)? This project has a single package.json and webpack.config(s) at the project root directory.

I'm about to try this out. Can anyone provide any advice for getting this to work? I see that the vue-example has its models in the client src directory. Not sure if that app is doing server-side validation using those models. Is this the recommended method? I will post my results back here soon. Thank you.

Saving only changed and valid fields

I am looking to use vue-contextable to facilitate saving of only the fields that are both changed and valid. To do this I will need to:

  1. have an efficient method of querying whether any fields in the model are both changed and valid (e.g. to disable save button in a similar way to using hasErrors()). I was hoping to add a version of isChanged() which includes evaluation of isValid() in addition to whether the value has changed from the initial value.
  2. to extend the commit method of the model and fields to only commit fields that are valid and to return the names and values of only the fields that have been commited in a form that can be dispatched via a rest api for syncing changes with the database backend.

I had considered extending the ReactiveModel and Field classes and base the code for the new methods on the existing methods implemented (isChanged and commit). However, it is not clear to me how I would indicate for vue-contextable to use these extended classes instead of the existing classes. The other alternative is to define these new methods as instanceMethods on the Schema โ€“ I can see how this is done, but it would seem more complex to implement due to the need to handle nested models.

If you have any suggestions on the best approach to implement this functionality, I would appreciate the advice.

Using Vuex

What's the best way to load in data from Vuex for a form? Everything from a getter is displaying an empty string that won't update when the data comes in.

Nested models and reactivity

I'm not quite sure if this is an issue with vue-rawmodel or Vue.js. but it seems that the support for nested models is limited or broken. Please see this demo for reference: https://codepan.net/gist/a7fe8b888cf6b5e92c84350e9ed22fbc

Basically I have two reactive models, where one model is a child of the other.

class MyModel extends ReactiveModel {
    name: string;
    locked: boolean;
    settings: Settings;

    public constructor({parent, ...data} = {}) {
        super({parent});

        this.defineField('name', { type: 'String', defaultValue: '' });
        this.defineField('locked', { type: 'Boolean', defaultValue: false });
        this.defineField('settings', { type: Settings, defaultValue: function() { return new Settings(); } });
    }
}

class Settings extends ReactiveModel {
    dummy: boolean;

    public constructor({parent, ...data} = {}) {
        super({parent});

        this.defineField('dummy', { type: 'Boolean', defaultValue: true });
    }
}

I have a custom form component named form-toggle looking like this:

Vue.component('form-toggle', {
  props: {
    value: { type: Boolean },
    onValue: { type: Boolean, default: true },
    offValue: { type: Boolean, default: false }
  },
  template: `<div>
    	<div class="toggle" :class="{on: isOn}">
        <div class="val" :class="{active: !isOn}" @click="turnItOff">off</div>
        <div class="val" :class="{active: isOn}" @click="turnItOn">on</div>
        <div class="marker"></div>
    	</div>
    </div>`,
  computed: {
    isOn: function() { return this.value === this.onValue }
  },
  methods: {
    turnItOn: function() { this.$emit('input', this.onValue); },
    turnItOff: function() { this.$emit('input', this.offValue); }
  }
});

And now we put it all together:

new Vue({
  el: "#app",
  data: {
    hasChanges: false,
    myModel: new MyModel()
  },
  computed: {
    status: function() { return this.hasChanges ? 'changed' : 'vanilla' }
  },
  methods: {
    stateChanged: function() {
      this.hasChanges = this.myModel.isChanged();
    },
    reset: function() {
      this.myModel.$rollback();
      this.hasChanges = this.myModel.isChanged();
    }
  }
});
</script>

For conveniance here's the template:

<div id="app">
  <h2>Model status: {{ status }}</h2>
  <div>
    <label for="name">
      Name:
      <input id="name" v-model="myModel.Name" @input="stateChanged" />
    </label>
  </div>
  <div>
    <p>Locked: {{myModel.locked}}</p>
    <form-toggle v-model="myModel.locked" @input="stateChanged"></form-toggle>
  </div>
  <div>
    <p>settings.dummy: {{myModel.settings.dummy}}</p>
    <form-toggle v-model="myModel.settings.dummy" @input="stateChanged"></form-toggle>
  </div>
  <button @click="reset">Reset</button>
  
  <h2>
    Raw output:
  </h2>
  {{ myModel }}
</div>

When I change the value of a non-nested property I'm unable to change the value of a nested property until I either reset ($rollback) the model or change the values back to their original state.

It feels like I'm missing something very obvious, but I've been trying to figure this one out for quite some time now. Hopefully you can shine some light on this?

Clarification of how to use nested schemas/models

I am having a little difficulty understanding how to properly use nested schemas. In the objectschema example I see that there is a nested schema (the field books has a type of [bookSchema]) in the user schema. I am clear on defining the schema but I am not sure how to use this operationally in vue.

For example if I have a form in the template which enables editing of the details of all books in addition to the user details.

  1. if I wish to have a button for adding additional books how do I code for this.
    e.g. my guess would be to use something like this.user.books.push({ title: 'True Detective' }), but this does not seem to work properly.

  2. I also am having some issue with v-model on the nested models.
    e.g. I am attempting to display fields for all the nested models. In terms of the user/book example it would be something like this for the first book in the array

{{ user.books[0].$title.errors | firstMessage }} I find that the user.books[0].title value of the model is not updated when I change the value in the form field (e.g. if I include {{ user.books[0].title value }} in the template to track this) and hence the rest of the methods/properties (e.g. hasErrors, errors) are not updated either. If I use a simple data object instead of the schema object this issue does not occur. I notice that when I change the value of a form field bound to a field such as user.name it triggers the user.books[0].title value to be updated such that it matches what is in the form field. Any insight into what I am doing wrong would be appreciated.

Decorator support

Allow for fields static method

http://aliolicode.com/2016/05/07/typescript-static-members/

https://github.com/xpepermint/vue-rawmodel/blob/master/src/models.ts#L29

public constructor (data: ReactiveModelRecipe = {}) {
    super(data);
    // ...
    let clazz = this.constructor;
    fields = fields || typeof clazz.fields === 'function' ? clazz.fields() : clazz.fields
    if (fields) this.defineFields(fields)
  }
import {ReactiveModel} from 'vue-rawmodel';

class User extends ReactiveModel {
  constructor (data = {}) {
    super(data); // initializing parent class
  }

  static fields() {
    return {
      name: {
        type: 'String', // setting type casting
        validate: [{
            validator: 'presence', // validator name
            message: 'is required' // validator error message
          }
        ]
      }
    };
  }
}

Equivalent to calling

  constructor (data = {}) {
    super(data); // initializing parent class
    this.defineField({
      // ...
    }
  }

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.