Giter Site home page Giter Site logo

vue-validator's Introduction

vue-validator - DEPRECATED

CircleCI Status codecov npm package

Validator component for Vue.js

⚠️ Please note, this project is deprecated and no longer being maintained

I recommend that you use other validation libraries. Thank you for everything you have done for vue-validator.

⚠️ NOTE: official release for Vue.js 2.0 not yet 🚧

⚠️ NOTICE !!

vue-validator have retiring from vue.js official plugins. in the future, vue-validator is continuing as personal project.

🆗 Compatibility

  • v2 later
    • Vue.js 1.0.20+
  • v3 alpha (WIP 🚧)
    • Vue.js 2.0.3 later (2.2 later, not works)

📖 Documentation

⭐ Projects

💪 Contributing

  • Fork it !
  • Create your top branch from 2.x: git branch my-new-topic origin/dev
  • Commit your changes: git commit -am 'Add some topic'
  • Push to the branch: git push origin my-new-topic
  • Submit a pull request to 2.x branch of kazupon/vue-validator repository !

🍃 Branch

  • dev (developement branch for v3 later)
  • 2.x (maintance branch for v2 later)

🔨 Development Setup

# install deps
npm install

# build dist files
npm run build

# lint
npm run lint

# run unit tests only
npm run unit

# run e2e tests only
npm run e2e

# lint & run all tests
npm test

❗ Issues

Please make sure to read the Issue Reporting Checklist before opening an issue. Issues not conforming to the guidelines may be closed immediately.

🚀 Contribution

Please make sure to read the Contributing Guide before making a pull request.

📜 Changelog

Details changes for each release are documented in the CHANGELOG.md.

©️ License

MIT

vue-validator's People

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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 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

vue-validator's Issues

Dynamic setting field, how to set up validator

code:

http://jsfiddle.net/lynzz/8zx3cnh6/

Business scene , think through the following settings, create a form with validation:

var fileds = [{
    label: '标题',
    name: 'title',
    value: '我就是我',
    validate:'required',
    placeholder: '请填写标题'
}, {
    label: '描述',
    name: 'description',
    value: '我就是我,是颜色不一样的烟火',
    validate:'required',
    placeholder: '请填写描述'
}];

Encountered do not know how to set v-model and validate issues.

PS: forgive my poor English

need a equals function

I think it's important to have a equals function, like:

<input type="password" placeholder="repeat password" v-model="rePassword" v-validate="equals:password">

Bug in the validator?

Consider the following example:
https://jsfiddle.net/q7xcbuxd/37/

Then remove the apostrophes from the mode variable to make it an integer and run the example again. Click on "second", then "first".

data: {
    mode: 0
}

Result:
The form gets initialized to dirty, then when clicking on the radio buttons a couple of times it starts to work as expected again. The reason is probably because it gets initialized as an integer and then turns into a string when clicking on "first", but the behaviour still seems a bit buggy, since it starts to work as expected after a couple of clicks. Setting value=0 instead of value="0" doesn't work either.

It's not neccessarily a bug in the validator though, it could also be that an integer is not a valid value for a radio button.

The child component cannot inherit validators defined in its parent.

Suppose we have a base Vue like the following

var base = new Vue({
  el: "#app",
  ...
  validator: {
    validates: {
      "username": require("./validator/username.js")
    }
  }
 components: {
   "my-component":  require("./my-component.vue")
 } 
});

and the child component is defined as follows:

<template>
  <input name="username" class="form-control" v-model="username"
             v-validate="required, username">
</template>
<script>
module.exports = {
  replace: true,
  inherit: true,
  data: function() {
    return  { username: "" };
  }
};
</script>

It seems that the child component cannot inherit validators defined in its parent.

unwatch is not a function

Hi,

I am getting this error when using validator "unwatch is not a function". When I comment out the line "$validator._undefineModelValidationScope(key)" everything works again.

Cheers!

Sauce labs error

https://travis-ci.org/vuejs/vue-validator/builds/56373710

npm WARN package.json [email protected] No README data
npm WARN package.json [email protected] No README data
npm WARN package.json [email protected] No README data
npm WARN package.json [email protected] No README data
npm WARN package.json [email protected] No README data
npm WARN package.json [email protected] No README data
npm WARN package.json [email protected] No README data
INFO [karma]: Karma v0.12.31 server started at http://localhost:9876/
INFO [launcher]: Starting browser chrome 39 (Windows 7) on SauceLabs
INFO [launcher]: Starting browser firefox 33 on SauceLabs
INFO [launcher]: Starting browser safari 8 (OS X 10.10) on SauceLabs
ERROR [launcher.sauce]: Can not start chrome 39 (Windows 7)
  Failed to start Sauce Connect:
  Invalid Sauce Connect Credentials. 30 Mar 06:13:07 - Error: GET https://saucelabs.com/rest/v1/undefined/tunnels?full=1: HTTP response code indicated failure.
30 Mar 06:13:07 - Error: response: {"error": "Not authorized"}.
30 Mar 06:13:07 - Error: failed to remove matching tunnels.
30 Mar 06:13:07 - Cleaning up.
30 Mar 06:13:07 - Finished! Deleting tunnel.
ERROR [launcher.sauce]: Can not start firefox 33
  Failed to start Sauce Connect:
  Invalid Sauce Connect Credentials. 30 Mar 06:13:07 - Error: GET https://saucelabs.com/rest/v1/undefined/tunnels?full=1: HTTP response code indicated failure.
30 Mar 06:13:07 - Error: response: {"error": "Not authorized"}.
30 Mar 06:13:07 - Error: failed to remove matching tunnels.
30 Mar 06:13:07 - Cleaning up.
30 Mar 06:13:07 - Finished! Deleting tunnel.
ERROR [launcher.sauce]: Can not start safari 8 (OS X 10.10)
  Failed to start Sauce Connect:
  Invalid Sauce Connect Credentials. 30 Mar 06:13:07 - Error: GET https://saucelabs.com/rest/v1/undefined/tunnels?full=1: HTTP response code indicated failure.
30 Mar 06:13:07 - Error: response: {"error": "Not authorized"}.
30 Mar 06:13:07 - Error: failed to remove matching tunnels.
30 Mar 06:13:07 - Cleaning up.
30 Mar 06:13:07 - Finished! Deleting tunnel.
make[1]: *** [test] Error 1
make[1]: Leaving directory `/home/travis/build/vuejs/vue-validator'
make: *** [sauce1] Error 2
npm ERR! Test failed.  See above for more details.
npm ERR! not ok code 0
The command "npm test" exited with 1.

onSubmit display errors

For a real use case i will use dirty flag to make sure the errors are not visible by default , but i want to show them if someone tries to hit the submit button. I know i can make it disabled by default but still if i am not going to make it disabled what is the other way around ?

Custom validator params

Hi

Does anyone know if there's a way to pass anything other than a string to a custom validator? My use case is as follows:

I have a form field that is only displayed (via v-show) if another field (radio button) is set to a certain value by the user. I have this working fine. What I'd now like to do is only require this field if is being displayed so basically I need a custom validator along the lines of requiredIf .

In proto code my app.js looks like this:

data: {
    response: '",
    approveMessage: "",
    declineMessage: ""
},
validator: {
    validates: {
        requiredIf: function(val, condition){
            console.log(condition);
            // My required logic goes here
        }
    }
}

On my form fields I have the following:

<label for="response">How do you want to respond?</label>
<input id="response_approve" v-model="response" checked="checked" name="response" type="radio" value="approve">
<label for="response_approve" >approve</label>

<input id="response_decline" v-model="response" name="response" type="radio" value="decline">
<label for="response_decline" >decline</label>


<div v-show="conditionalField('response', 'approve')" v-class="has-fe-error: validation.approved_message.invalid">
    <label for="approved_message">Approved message</label>
    <textarea v-model="approved_message" v-validate="requiredIf: conditionalField('response', 'decline'), maxLength: 500" name="approved_message" cols="50" rows="10" id="approved_message"></textarea>
</div>

<div v-show="conditionalField('response', 'decline')" v-class="has-fe-error: validation.declined_message.invalid">
    <label for="declined_message">Declined message</label>
    <textarea v-model="declined_message"  v-validate="requiredIf: conditionalField('response', 'decline'), maxLength: 500" name="declined_message" cols="50" rows="10" id="declined_message"></textarea>
</div>

In this example the method called conditionalField just get's pass through as a string (the method itself shows/hides fields just fine so I know it works) and if instead I use an inline expression such as:

v-validate="requiredIf: response == 'decline'

this also get's passed through as a string. Is there any way to pass through either a method, an inline expression or even just more than one expression after the requiredIf argument?

something is wrong with vue-router

When i use the vue-validator, the vue-router goes wrong. nothing is appeared after i navigate the url.
When i remove the Vue.use(require('vue-validator')), vue-router is ok.
I'm using vue-router0.5 , vue.js 0.12.10.

Using this.$data creates an issue

Perhaps I am using the validator incorrectly. But for a specific case I am fetching some content using an ajax call inside a ready method and then wanting to set the content using this.$data. It would be cleaner if I can do that instead of setting every single property individually.

However as soon as I do that I get the following error from the console.

[Error] TypeError: undefined is not an object (evaluating 'last[key]')
    getTarget (bundle.js, line 1231)
    _doValidate (bundle.js, line 1207)
    (anonymous function) (bundle.js, line 9411)
    (anonymous function) (bundle.js, line 1138)
    wrappedCb (bundle.js, line 1362)
    run (bundle.js, line 10256)
    run (bundle.js, line 2109)
    flush (bundle.js, line 2095)
    handle (bundle.js, line 9246)

Here is a simplified fiddle to illustrate.

It works if I use this.name = 'Caspien' or this.$set('name', 'Caspian') inside the ready function.

Improvement to the resetDirtyFlags function

Sup guys!

As I've mentioned earlier, I've made a custom resetDirtyFlags function so that the dirty flags can be reset during the application lifespan, for example after fetching new async data from the server. However, the previous function only worked for properties one level deep. I've now extended it to go two levels deep (ideally I'd make it recursive, but two levels will do for now).

So for example, given the following code:

data: {
   text: "abc",
   sub: {
       text: "abc"
   }
}

the improved function will now reset the dirty flags on both textand sub.text.
So in case anyone's interested, here's the code:

resetDirtyFlags: function(comp){
    for (var property in comp.validation) {
        //goes two levels deep
        for (var subProperty in comp.validation[property]) {
            if (comp.validation[property][subProperty].hasOwnProperty("valid")){
                //console.log(property + " " + subProperty + " " + comp.validation[property][subProperty]);
                comp.$validator._setInitialValue(property+"."+subProperty, comp.$data[property][subProperty]);
                comp.$validator._updateDirtyProperty(property+"."+subProperty, comp.$validator[property][subProperty]);
            }                   
        }
        //console.log(property);
        //goes one level deep:
        comp.$validator._setInitialValue(property, comp.$data[property]);
        comp.$validator._updateDirtyProperty(property, comp.$validator[property]);
    }
}

😸

Question about the dirty property

Hi!

I'm not sure if this is a bug or if it's supposed to be like this, but the dirty property will only work if the element has a v-validate property.

Sometimes, it would be nice to see if a property (or a form) is dirty without putting an actual validator on every single element in the form. v-validate="" doesn't work, so I guess the only way to do this at the moment is to write a custom validator that always returns true, or to use something like v-validate="minLength: 0"

Example:
https://jsfiddle.net/q7xcbuxd/31/

Custom validators in v-repeat

Hey, I stumbled upon this and thought it would be best to report this issue, even though I think it is being adressed in v2.0.

I created a pen to demonstrate the behaviour (vue 0.12.13, vue-validator 1.4.3): http://codepen.io/tuelsch/pen/ojjoMR?editors=101

If the custom validator is used inside the v-repeat, a warning shows up in the console: [vue-validator] specified invalid v-validate directive !! please check v-validator directive !!. The built-in validator required works as expected (switch the attribute on the input field).

Is there a way to fix this by defining the custom validator differently or is this a bug?

Thanks for the very handy library and your effort!

Exception when using v-if (reapplying validator to the same model multiple times)

Here's a fiddle: http://jsfiddle.net/davidkhess/68z6uqff/1/

Using Vue 0.12rc2 and the latest vue-validator.

If you click the toggle button 3 times, on the third click there is an exception:

[Error] TypeError: undefined is not an object (evaluating 'this._validators[keypath].forEach')
    _doValidate (vue-validator.js, line 334)
    (anonymous function) (vue.js, line 442)
    bind (vue-validator.js, line 118)
    _bind (vue.js, line 8061)
    Directive (vue.js, line 8036)
    _bindDir (vue.js, line 7906)
    nodeLinkFn (vue.js, line 2463)
    childLinkFn (vue.js, line 2181)
    childLinkFn (vue.js, line 2184)
    compositeLinkFn (vue.js, line 1913)
    compile (vue.js, line 6931)
    update (vue.js, line 6919)
    (anonymous function) (vue.js, line 8072)
    run (vue.js, line 3409)
    run (vue.js, line 4256)
    flush (vue.js, line 4241)
    handle (vue.js, line 662)

Bug with validator when using with component and filter

Hi,

See this link https://jsfiddle.net/silasrm/8L61dt58/4/ with developer tools/firebug open.

Explain:
My app have a list with component working with v-repeat:

This is ok. But I need to add a search field to searching in list item:

And change de v-repeat to: v-repeat="itens | filterBy search"

When I add letter, this filtering list, but when I remove letter to clear search term, occurs this error:
Uncaught TypeError: Cannot read property 'push' of undefined

Thank's.

validator doesn't resolve dynamic models

I have inputs that are dynamically created, so i may have a model that is set to v-model="entityModel[key]". The key could be from a iterating array. Vue validator doesn't resolve the key, so if the key were test, instead of entityModel.test i end up with entityModel[key]. Any way around this?

Is there a way to initialize validation without propVal ?

I want to initialize the validation after click the submit button...how can i do ?
maybe i need a 'wait-for-all' attribute on every model to disabled all the model's validation, and initialize the validation after click submit button or text something in one of the models.

List of invalid fields

For debug purposes and easier listing invalid filled fields: list of invalid fields.

For example:

validation method:

validName: {
    message: function(el){
        return "between 5 and 10 characters";
    },
    check: function(v){
        return v.length >= 5 && v.length <= 10;
    }
}

HTML:
<input v-model="form.name" name="companyName" v-validate="validName"/>

<li v-for="error in validation.fields"><span v-text="error.fieldName"></span>: <span v-text="error.message"></span></li>
</ul>``` 

where `error.fieldName` is input's name and `error.message` contains what `message` method returns (element given as parameter

Add a 'pristine' property, or change the way 'dirty' behaves

I was hoping dirty would work the opposite of angular forms' pristine, but that doesn't seem to be exactly the case.

It would be useful to have a property that keeps track of whether a model has ever been changed

Imagine a signup form with a required username field, initially empty.

I don't want to have an error showing up as soon as the page loads, telling the user they've done something wrong even though they haven't interacted with it yet.

I do want to inform them that it's a required field if they type something in, then delete it

The way dirty currently behaves is that it only checks if current value != initial value, might be better if it was renamed to modified and have dirty keep track of whether the value was ever changed at all. Or have a pristine property that keeps track of the same thing.

As a reference, here's how Angular's formcontroller handles the variables:

$pristine
boolean 
True if user has not interacted with the form yet.

$dirty
boolean 
True if user has already interacted with the form.

v-validate does not work with v-class

My html code

<div class="current_page item">
    <div class="ui input" v-class="error: validation.current_page.invalid">
        <input type="text" v-model="current_page" number v-validate="min: 1, max: 9" v-on="keyup: onGoToPage | key 'enter'">
    </div>
</div>

Whatever numbers typed in the field, the v-class won't work.

validation.model.validator 无法使用keypath获取model

您好!非常感谢您提供的validator,在以下应用场景出了点问题。

  <input type="text" class="form-control"  v-model="company.org_name" v-validate="required">
  <div>
    <span v-if="validation.company.org_name.required">required your company org_name.</span>
  </div>

validation.company.org_name.required 无法正确的获取到model, 在线急等。

Dirty on remote data? / Delay validation until data is loaded

<template>
                <form accept-charset="utf-8" method="POST">
                    <div class="form-group required">
                        <label for="name" class="form-label">Name</label>

                        <div class="controls"><input id="name" class="form-control" type="text"
                                                     v-model="client.name" v-validate="required,minLength:3"></div>
                    </div>

                    <div class="form-actions"><input class="btn-primary btn" type="submit" value="Save Client" v-attr="disabled: invalid || !dirty"></div>
                </form>
</template>
<script>
    module.exports = {
        replace: true,
        props: ['params'],
        data: function () {
            return {
                params: {
                    clientEditId: null
                },
                client: null
            }
        },
        compiled: function () {
            this.update()
        },
        watch: {
            'params.clientEditId': 'update'
        },
        methods: {
            update: function () {
                var resource = this.$resource('/client/client/:id');
                resource.get({id: this.params.clientEditId}, function (item, status, request) {
                    this.client = item
                    this.dirty = false //doesn't work!
                }.bind(this))
            }
        },

    }
</script>

In this example, dirty() is always false, because the data->client has been changed from its initial state of null.

How can we disable validation until the data is loaded?

Or set dirty = false, once the object has been loaded?

Thanks!

Bug with the dirty-function?

Hi guys! I've tried everything and I still can't get the dirty function to work properly, except when the data value is a number.

I initialize the form and set a string value, but as soon as the form loads, the validator thinks it's dirty. And when the text is removed, it thinks it's not dirty (even though it is).

Am I doing something wrong here?

https://jsfiddle.net/q7xcbuxd/10/

"Error when evaluating expression validation.name.invalid"

Hi,

great work on this plugin!

When I access to the validation object, i got in the console the following message:

[Vue warn]: Error when evaluating expression "validation.name.invalid"

While this doesn't break the application I wonder if I'm missing something in the setup.

Thanks in advance!

Travis setting

@vuejs/owners
I could not run the travis-ci.
I want to run the travis-ci.
Would you set the travis-ci ?

The following is a screen when an error occurs at the travis-ci.
screen shot 2015-01-31 at 1 39 17 am

How can I do validation depending on another field?

Using following codes,

vm = new Vue({
  data: {
    password: '',
    reenteredPassword: ''
  },
  validator: {
    validates: {
      matchPassword: function(v) {
        return v === this.password;
      }
    }
  },
  // SNIP..
<div>
    <div>
        <label>Password</label>
        <input type="password" v-model="password" />
    </div>
</div>
<div>
    <div>
        <label >Confirm password</label>
        <input type="password" v-model="reenteredPassword" v-validate="required, matchPassword" />
    </div>
    <div v-show="validation.reenteredPassword.dirty">
        <div v-show="validation.reenteredPassword.matchPassword">doesn't match password</div>
    </div>
</div>

if you change reenteredPassword and it doesn't match password, validation will be updated and doesn't match password will be displayed. But if you change password and it doesn't match reenteredPassword, validation will not be updated.

How can I do validation depending on another field? Or, how can I perform validation explicitly on watcher like vm.$watch('password', function.. ?

Feature request: touched indicator (like AngularJS $touched)

It would be nice to have a validation.model.touched that is set when a control blurs after receiving focus. If a field starts off invalid, then dirty isn't sufficient to cause error display if they visit the input but don't change the value.

BTW, nice plugin!

Validation on child items

Trying to get validation to work when using a v-repeat directive, as per fiddle. (Sorry I had to paste the contents of vue-validator as part of the js otherwise it did not work using github as a raw resource).

Is it possible to use the validator like this?

Async validation?

Using Promises?

    validator: {
      validates: {
        email: function (val) {
          return /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(val)
        },
        remote: function (val) {
          new Promise(function (resolve, reject) {
            setTimeout(function () {
              if (val.length > 3) {
                return resolve(true)
              }
              return reject();
            }, 500);
          });
        }
      }
    },

There is a small error in README

I found minor error code in "validation of all models" as below.
As is:
<span v-if="validation.id.minLength">too long your ID.</span>
should be...
<span v-if="validation.id.maxLength">too long your ID.</span>

Feature request: make v-validate reactive

It appears that v-validate is a literal directive. It would be nice if it were reactive so that you could enable or disable validations under certain conditions. For instance, for a field that is sometimes required.

EDIT

I suppose a workaround (or perhaps what is the intended solution) would be to use a custom validator in this case.

loadmap

v1.0.7

This version is the last of supported version of Vue.js 0.11.

  • unbind bug fix #19

v1.1.0

This version is supported Vue.js 0.12.

  • support Vue.js 0.12 (#23)
  • pattern validator change (pattern validator bug fix #17)

v.1.1.0 later

  • delay initialize of validation (#25)
  • v-validate reactive (#6)
  • function or inline expression like v-on (#40)
  • async validation (#10)

v2.0

This version is implemented with full scratch and new design

- [ ] v-validate reactive (#6)
- [ ] async validation (#10)

  • improve delay initialize of validation (wait-for) (#25)
    - [ ] array-able validation (#31)
  • improve/add validation property (dirty, pristine, and other) (#33)
    - [ ] input[type='file'] validation
    ~~- [ ] add build-in validators ~~
  • dynamic validator setup (#46)
  • multiple validators (#18)
    - [ ] HTML5 form attributes (#22)
  • invalid error message (#51)
  • input debounce for async validation (#58)
  • events triggering (blur, submit, keyup, ... etc)

# v3.0
- [ ] input[type='file'] validation

2.0 plan

Hi everyone !!

I'm planning for the v2.0 release.
I will start development on dev/latest branch at an early date.

I have been publish the v1.0 release, fixed some bugs and adopted some user feedbacks.

I think that want to adopt the user coming feedback to v1.0 implementation, but v1.0 implementation is bad design.
Even if i adopting the user coming feedback, the bug occur easily.

For these reasons, I have decided to implement the v2.0 with full-scratch.

I did rework the specification once again.
The following specifications (sorry my poor english):

spec

  • custom element (e.g. <v-validator></v-validator>)
    • custom element enable validation result scope that did inherit from user data scope. vue-validator do not operate user data via validation result scope
    • id attribute: keep the validation result data in custom element (e.g. vm.$validators.validator1)
    • name attribute: change the validator result scope namespace (e.g. default: validity)
    • available multiple validator (e.g. vm.$validators.validator1, vm.$validators.validator2, ...)
  • set custom directive (v-validate) to target element
    • specify field name: keep the validation result
    • validation result format: object property base structure (e.g. validity.field.constraint)
    • accessable validation result with property keypath base (e.g. validity.username.xxx)
  • support for each field, the following validation property
    • valid (e.g. validity.field.valid)
    • invalid (reverse of valid, e.g. validity.field.invalid)
    • modified (from initial field value, e.g. validity.field.modified)
    • dirty (angluar-like, attached even once, e.g. validity.field.dirty)
    • pristine (angluar-like, not attached even once, e.g. validity.field.pristine)
  • support the following top level property that keep the validation result of all fields
    • valid (when all property is valid, return true)
    • invalid (if exist even one invalid property, return true)
    • modified (if exist even one modified property, return true)
    • dirty (if exist even one dirty property, return true)
    • pristine (if exist even one pristine property, return true)
  • build-in validators
    • required
    • pattern
    • min
    • max
    • minLength
    • maxLength
  • improve delay validator initialization feature
    • custom element base (not for each custom directive)
  • validator use HTML5 Form attributes base. (e.g. min, max ...)
    • support custom validator: use attribute (e.g. myValidator1 -> <input type="text" my-validator1="foo">)
    • support reactivity & function or inline expression like v-on: {{ mustache }} expressions (e.g. <input type="text" min="{{constraints.min}}">)
    • support async validator
  • validator assets feature
    • aseets management: like vue.js
    • register/retrieve custom validator or build-in validtors

sample code

<div id="app">
    <h1>user registration</h1>
    <v-validator id="validator1">
        <form>
            username:<input type="text" required maxLength="16" pattern="/[a-zA-Z0-9_-]/" exist v-validate="username"><br>
            age:<input type="number" required min="{{constraints.age.min}}" max="{{constraintAgeMax}}" v-validate="age"><br>
            email:<input type="email" required email v-validate="email"><br>
            password:<input type="password" required minLength="8" v-validate="password"><br>
            site:<input type="number" url v-validate="site"><br>
            <button type="submit" value="join" v-class="disabled: invalid"><br>
            <div>
                <span v-if="validity.username.required">required username.</span>
                <span v-if="validity.username.maxLength">too long username.</span>
                <span v-if="validity.username.pattern">invalid username format.</span>
                <span v-if="validity.username.exsit">already exist username.</span>
                <span v-if="validity.age.required">required age.</span>
                <span v-if="validity.age.min">too small age.</span>
                <span v-if="validity.age.max">too big age.</span>
                <span v-if="validity.email.required">required email.</span>
                <span v-if="validity.email.email">invalid email format.</span>
                <span v-if="validity.password.required">required password.</span>
                <span v-if="validity.password.minLength">too short password.</span>
                <span v-if="validity.site.url">invalid site url format.</span>
            </div>
        </form>
    <v-validator>
</div>
var Vue = require('vue')
var VueValidator = require('vue-validator')

//
// register custom validators with validator assets
//

// url validator, sync validation
VueValidator.asset('url', function (val) {
    return /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/.test(val)
})

// exist validator, async validaiton
Vuevalidator.asset('exist', function (val) {
    return function (resolve, reject) {
        // server-side validation with ajax (e.g. using `fetch` case)
        fetch('/validators/exist', {
            method: 'post',
            headers: {
                'content-type': 'application/json',
                'x-token': 'xxxxxxxx'
            },
            body: JSON.stringify({ username: val })
        }).then(function (res) {
            if (res.status === 200) {
                resolve(true)
            } else if (res.status === 400) {
                resolve(false)
            }
        }).catch(function (err) {
            // something todo ...
            reject(new Error('exist validator fail'))
        })
    }
})

// email validator, async validation
VueValidator.asset('email', function (val) {
    return function (resolve, reject) {
        // something todo ...
    }
})

// install vue-validator
Vue.use(VueValidator)

// create Vue instance
new Vue({
    data: {
        constraints: {
            age: {
                min: 18,
            }
        },
        name: '',
        age: 18,
        email: '',
        password: ''
    },
    computed: {
        constraintAgeMax: function () {
            return this.constraints.age.min * 5
        }
    }
}).$mount('#app')

NOTE:
This is just a tentative specification.

Asynchronous validator should perform validation after user has finished the input

I have a form for registering new users. The form has a username field, and I use a asynchronous validator to validate whether the username exists (as described by the example in the README.md).

The problem is, the validator will try to validate as soon as the user enter a single letter. This will cause the server receives too many requests.

Is there any way to make the asynchronous validator perform the validation after the user has finished the input? That is, the validation should be performed after the input focus leaving the username field.

Thanks in advance.

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.