Code Monkey home page Code Monkey logo

validation's Introduction

Aurelia

License: MIT npm Version ci Discourse status Twitter Discord Chat

aurelia-validation

This library is part of the Aurelia platform and contains a plugin that provides validation capabilities.

To keep up to date on Aurelia, please visit and subscribe to the official blog and our email list. We also invite you to follow us on twitter. If you have questions look around our Discourse forums, chat in our community on Discord or use stack overflow. Documentation can be found in our developer hub.

Documentation

Check out the docs on the Aurelia Hub.

Reporting Issues

Please refer to the issue template. Accompany any bug report with a demo of the issue using a runnable Gist.

Building The Code

To build the code, follow these steps.

  1. Ensure that NodeJS is installed. This provides the platform on which the build tooling runs.
  2. From the project folder, execute the following command:
npm install
  1. To build the code, you can now run:
npm run build
  1. You will find the compiled code in the dist folder, available in three module formats: AMD, CommonJS and ES6.

Running The Tests

To run the unit tests, first ensure that you have followed the steps above in order to install all dependencies and successfully build the library. Once you have done that, proceed with these additional steps:

  1. You can now run the tests with this command:
npm run test

You can optionally run either of the following:

npm run test:watch
# OR
npm run test:debugger

to have better development experience, with watch/debuging capabilities

Publishing

Refer to ./doc/MAINTAINER.md for details.

validation's People

Contributors

aaike avatar behzad888 avatar bfil avatar bigopon avatar bulldetektor avatar charlespockert avatar cmichaelgraham avatar cuddlebunny avatar dkent600 avatar eisenbergeffect avatar erikschierboom avatar fabioluz avatar fkleuver avatar janvanderhaegen avatar jdanyow avatar jeroenvinke avatar jods4 avatar joshmccullough avatar manuel-guilbault avatar mbroadst avatar niieani avatar paulinfrancis avatar plwalters avatar rajwilkhu avatar robertherhold avatar romkevdmeulen avatar saqibnoorani avatar sayan751 avatar shingos avatar strahilkazlachev 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  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

validation's Issues

Allow ensure('bindingPath') to be configured

ensure('bindingPath') should take an optional second parameter that provides settings for this specific binding path.
Examples could be:

  • per property debounce time (we could reset default debounce time to a lower value and allow per-property higher debounce times)
  • dependencies (allows a property to be re-evaluted if a dependency changes value)
  • ...

Validation object not getting injected

I have this class

import {Validation} from 'aurelia-validation';
export class SignupModel {
     static inject() { return [Validation]; }
     constructor(validation) {
        console.log(validation); // logs as: undefined
        this.userName = '';
       this.validation = validation.on(this)
            .ensure('userName')
            .isNotEmpty()
            .hasLengthBetween(3, 10);
     }
}

I have also added the plugin to main

export function configure(aurelia) {
  aurelia.use
    .standardConfiguration()
    .developmentLogging()
    .plugin('aurelia-validation')
    .plugin('./resources/index'); 

  aurelia.start().then(a => a.setRoot());
}

But not sure why, validation object is undefined in constructor.
Am I missing something?

ValidateAttachedBehavior does not match bindings with a valueConverter

this.validation = validation.on(this).ensure('firstName').notEmpty()
<div validate.bind="validation">
  <input value.bind="firstName | toUpper" />
</div>

In this scenario,the validateAttachedBehavior does not match the binding path of the input element ('firstName | toUpper') to the binding path of the validation (ensure('firstName')). If the ValidateAttachedBehavior were smart enough to trim out spaces and valueConverters, it would be able to match the two binding paths.

AJAX validation support

Suggestion by @devmondo (moved from old plugin repository):
i dont know if i missed it or it is not there yet, but AJAX validation is really needed, specially for cases where you want to check duplicate username on server in create account scenarios

thanks in advanced.

Object properties don't work with default viewstrategy

If you bind to a property on an object the default (bootstrap) view strategy never finds the property for the binding string

e.g.

<input value.bind="someObject.someProperty"></input>

The code in the view strategy only strips the value converters from the binding but doesn't look at the dots

Simple fix would be to strip off anything before the last index of "." in the binding string in the view strategy:

 // Remove any dotted parts to the binding path as the validator deals with just the prop name
 if (bindingPath.indexOf('.') != -1)
     bindingPath = bindingPath.substring(bindingPath.lastIndexOf(".") + 1);

Then it will work a bit nicer for bootstrap out of the box

Split documentation

ReadMe.MD is becoming too large to be useful... tl;dr
Need to split this into a quick 'overview'/'cheat cheat'/'example' page and multiple 'deeper dive' documents/examples...

Validation should pick up @computedFrom annotation

Properties can be re-evaluated based on dependent properties, this is done using a config callback and calling (config) => {config.computedFrom(['anotherProperty'])}
However, if this property already has an aurelia @computedFrom annotation, this should automatically be picked up.

Support functions as treshold

The validation plugin currently only supports constant tresholds, for example:

this.validation = validation.on(this).ensure('password').isStrongPassword();

We also need to support dynamic values, for example:

this.validation = validation.on(this).ensure('confirmPassword').equals( this.passWord);

validation package does not export ValidateCustomAttributeViewStrategyBase

I'm attempting to create a custom validation strategy; according to the docs this should be sufficient:

validation.js:

import {ValidateCustomAttributeViewStrategyBase} from 'aurelia-validation';

export class CertChiefViewStrategy extends ValidateCustomAttributeViewStrategyBase {
  constructor() {
    super();
  }

  ...
}

Then configure the app to use the new validation strategy:

import {CertChiefViewStrategy} from './validation';

export function configure(aurelia) {
  aurelia.use
    .standardConfiguration()
    .developmentLogging()
    .plugin('aurelia-animator-css')
    .plugin('aurelia-validation', (config) => {config.useViewStrategy(new CertChiefViewStrategy())})
    .plugin('aurelia-bs-modal');
  aurelia.start().then(a => a.setRoot('app', document.body));
}

However, I get this nice error: Super expression must either be null or a function, not undefined

If I copy the ValidateCustomAttributeViewStrategyBase code into my class, everything is fine. Is this a bug in the validator, framework, loader...?

Consider json-schema

It would be interested if we could build up a validation configuration based on json-schema. http://json-schema.org/ This is a lower priority than other issues. Just putting it here for a possible future addition.

noSpaces

Would also be handy to ensure fields don't have spaces.

.matches(/^\S*$/); //no spaces

Important Contributing Practices

All commit messages need to adhere to the contributing guidelines. Also, each release should be done with the prepare-release gulp test to ensure that the proper change log is generated into the docs folder. The change notes particular to the release should be part of the github release notes. This needs to be done to be consistent with all other Aurelia libraries.

Need support for custom backend subject validation

In contrast to #3, we need support to do an ajax call with the entire subject, then have the result 'dictate' the state of the entire validation. This stand-alone or in combination with client-side validation.

API is inconsistent

The API currently asks some validation rules to be added using functions prefixed by 'is':

  • isStrongPassword()
  • isAlphanumeric()
  • ...

This is inconsistent with the more 'verb-less' validation rules:

  • email()
  • minLength()
  • notEmpty()

TODO: decide on most desired API, then refactor so that they are consistent:

this.validation = validation.on(this)
  .ensure('user.email').email()
  .ensure('user.password').strongPassword();

this.validation = validation.on(this) 
  .ensure('user.email').isEmail()
  .ensure('user.password').isStrongPassword();

Personally I'd prefer the latter: having a 'verb' in each function that indicates a validation rule being executed. This is longer but

Add support for chriso's validator (chriso/validator.js)

Introduction

Validating webforms, response data and other forms of information is a common task. Therefor, I believe it's important to make sure it's easy to do and doesn't cause any performance issues.

NIH?

I'm not sure what Aurelia's policy is on this, but I personal prefer using existing libraries which have proven themselves over time.

A great example of this is chriso's validator (chriso/validator.js). It has built-in string validators and works really well. Sails.js uses it in Anchor (balderdashy/anchor) with added object validation and more.

In comes Aurelia

I'm again not quite sure how Aurelia would like to use this. I think that supplying a common format of using the validator is the way to go. We could then bind objects to the validator, and have them validate when asked.

I have two ideas on how to do this.

Validated entities

We could create the concept of "validated entities". An entity is simply a class with defined rules (properties and their validation and filtering). These entities will be used to construct objects of data, validate the data they hold and return filtered data. This could be useful for validating and filtering responses from API calls, as well as validating and filtering data that is to be sent to an API. An example:

class AbstractEntity {
  validate () { }

  isValid () { }

  getErrors () { }

  setData () { }

  getData (raw) { }
}

export default class UserEntity extends AbstractEntity {
  construct () {
    this.rules = {
      username : {
        type    : 'string',
        required: true,
        regex   : /^[\w\-]{2,14}$/
      },
      password : {
        type : 'string',
        required: true,
      }
    };
  }
}

Library

The other method requires less work, and simply offers validation as an import. The developer uses the library the way he or she wants to without having to follow any conventions.

What do you think?

This is just a quick proposal I wanted to post to start a conversation.

UX: add 'success' to properties that have no validation rules

Suggestion: consider properties that have no validation rules to be valid when .checkAll() is called.

Motivation: Suppose there's a contact entity with firstName, lastName, email and notes properties.
Validation is added for firstName, lastName and email.
When the checkAll() is called on the validation, there will be visual feedback that the input fields for firstName, lastName and email are valid/invalid, but there will be no visual feedback that the input field for notes is either valid or invalid.

Investigate memory usage (destroy)

Since aurelia/validation depends on observers, there should be a proper way to clean up (destroy) a validation when it is no longer needed.

Should trailing spaces be trimmed

The current implementation trims trailing spaces:
" " passes notEmpty(),
" a " passes isMaxLength(2);

Is this behavior even required by anyone?

Support both model-first and view-first implementations

The framework currently supports model-first: use a fluent API on your model to create the 'validation' object.
We can add custom attributes so that those who want to, can create the 'validation' object completely using attributes.

how do I reference `this` with validation?

I'm currently doing this:

  @ensure(function(it){
    it.isNotEmpty()
      .hasLengthBetween(3,100);
  })
    name = ''; //needs to be `this.thing.name` somehow

But I need to reference an object like this.thing.name instead. I'm moving the properties of the view model to a single object as children. so instead of name in my view I do thing.name etc. etc.

I can't figure out how to get the @ensure validation to work if I make this change.

Need support for debouncing

If a userName property is wired up to an AJAX call for validation, we need debouncing, ie not run while the user is typing but only when the user hasn't changed the value for X ms.

WithMessage

Hi,

I'm getting an error with this code:

    this.username = '';
    this.password = '';

    this.validation = validation.on(this)
      .ensure('username')
        .isNotEmpty()
        .withMessage('Username is required')
      .ensure('password')
        .isNotEmpty()
        .withMessage('Password is required');

An error:

inner error: TypeError: Cannot read property 'withMessage' of undefined
    at ValidationRulesCollection.withMessage (http://localhost:1337/jspm/github/aurelia/[email protected]/validation/validation-rules-collection.js:121:66)
    at ValidationGroupBuilder.withMessage (http://localhost:1337/jspm/github/aurelia/[email protected]/validation/validation-group-builder.js:204:47)
    at ValidationGroup.withMessage (http://localhost:1337/jspm/github/aurelia/[email protected]/validation/validation-group.js:299:33)

What am I doing wrong?

I18N cannot contain logic in the validation messages

Our current I18N implementation relies on keys to be matched to a function. Two of these functions contain logic to return a different translation based on parameters.
Unfortunately, most I18N frameworks, including aurelia's upcoming own I18N implementation, match keys to strings (which allow format parameters).
To make our I18N custom implementation pluggable, aurelia-validation must be refactored so that any logic to pick the right translation based on the situation, is moved outside the I18N classes.

Support 'foreach'

Desired:

this.validation = validation.on(this)
  .ensure('orderItems')
    .minLength(1)
  .ensureForEach('orderItems')
    .ensure('qty')
       .minimumValue(1);
```  .

Support 'all fields are mandatory'

Currently, all fields are optional. You have to signal every required field using .isNotEmpty().

The inverse should be possible too: all fields are required, dev has to signal optional fields using .canBeEmpty() or .isOptional().

Comments on best API?

isUrl?

Would be nice to have an isUrl validator

Validating a bounded property on a custom attached behavior causes a classList is undefined error

I have the following setup using the validation plugin

<form validate.bind="validation" submit.delegate="save()">

     <div class="form-group">
       <input type="text" class="form-control" value.bind="contract.client"/>
     </div>

      <lookup-widget title="Client" placeholder="Find Client..." value.two-way="contract.client"></lookup-widget>

      <button type="submit" class="btn btn-default">Save</button>
    </form>
</template>

When you run the application an error occurs saying "classList is undefined". Going through the validation source in file validate-attached-behavior.js for the function searchFormGroup is assumes the element is a standard HTMLElement however the lookup-widget is a DocumentFragment which has no classList property. I assume because the way the widget is rendered via Aurelia that it's injected as a DocumentFragment.

So replicated steps would be to try and bind a property from a model on a custom widget (attached behaviour) where the property has been marked as to be validated.

this.validation = validation.on(this)
                        .ensure('contract.client').notEmpty()

Allow configuration during plugin loading

This plugin is currently loaded (registered with aurelia) in your main.js:

aurelia.plugin('aurelia-validation');

This method actually allows a second parameter, which will then be passed to the plugin's install function.
The idea is to allow the devs to pass a 'configuration callback' function, so that they can do initial configuration of the aurelia-validation plugin right when they register it with aurelia.

for example:

aurelia.plugin('aurelia-validation', (validation) => {
    validation.useLocale('nl-BE')
                   .viewStrategy(validation.viewStrategy.TwitterBootStrap);
});

Reset validation

Is it possible to reset validation? I need to reuse the form after AJAX action.

Feature Request: Breeze Validation Plugin

Hi, I was chatting with Jeremy Danyow about 'out of the box' validation with Breezejs, similar to the breeze angular validation plugin. Jeremy says it would be cool and suggested I run this past you :-D
Our chat ref:
https://gitter.im/Aurelia/Discuss?at=552fad1d8c86646906dd318e

And the angular validation plugin breeze provide is here:
http://www.getbreezenow.com/documentation/directivesvalidation

Just wondering what your thoughts are? I know the angular breeze validation plugin is extremely popular and would be an awesome plugin for aurelia and I'm sure Ward Bell would be very keen also.

I'm happy to help in any way I can.

Cheers
Paul

Discrepancies in config.js

Currently config.js references various versions of repos that could potentially be causing conflicts when loading.

Promises that finish late are not supported correctly

Suppose there's an AJAX call to validate a property.
User types "A", AJAX call for "A" is triggered
User types "AB, AJAX call for "AB" is triggered
AJAX call for "AB" finishes early: "AB" is valid.
AJAX call for "A" finishes late: "A" is invalid

Expected result: since the value is 'AB', the property is valid

Actual result: the AJAX call for "A" is the last one to finish and sets the result to invalid

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.