Giter Site home page Giter Site logo

ember-bootstrap / ember-bootstrap-cp-validations Goto Github PK

View Code? Open in Web Editor NEW
13.0 8.0 11.0 6.75 MB

ember-cp-validations support for ember-bootstrap

License: MIT License

JavaScript 86.86% HTML 9.77% Handlebars 3.36%
ember-bootstrap ember-cp-validations ember ember-addon

ember-bootstrap-cp-validations's Introduction

ember-bootstrap-cp-validations

npm version

This Ember addon adds support for validations based on Ember CP Validations to ember-bootstrap forms. This way your forms are only submitted when the underlying data is valid, otherwise the appropriate bootstrap error markup will be applied. See the FormElement documentation for further details.

Compatibility

  • Ember Bootstrap v4
  • Ember CP Validations v4
  • Ember.js v3.16 or above
  • Ember CLI v3.15 or above
  • Node.js v10 or above

Installation

ember install ember-bootstrap-cp-validations

You should have installed the ember-bootstrap and ember-cp-validations addons already. If not install them:

ember install ember-bootstrap
ember install ember-cp-validations

Usage

Define your model and its validations as described in Ember CP Validations:

import Ember from 'ember';
import { validator, buildValidations } from 'ember-cp-validations';

const Validations = buildValidations({
  username: validator('presence', true),
  email: validator('format', { type: 'email' }),
  password: validator('length', { min: 10 }),
});

export default Ember.Component.extend(Validations, {
  username: null,
  email: null,
  password: null,
});

Then assign the model to your form:

<BsForm @model={{this}} as |form|>
  <form.element @label="Username" @controlType="text" @property="username" />
  <form.element @label="Email" @controlType="email" @property="email" />
  <form.element @label="Password" @controlType="password" @property="password" />
  <form.submitButton>Submit</form.submitButton>
</BsForm>

Contributing

See the Contributing guide for details.

License

This project is licensed under the MIT License.

ember-bootstrap-cp-validations's People

Contributors

acorncom avatar dependabot-preview[bot] avatar dependabot[bot] avatar gustaff-weldon avatar jelhan avatar offirgolan avatar simonihmig avatar

Stargazers

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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ember-bootstrap-cp-validations's Issues

Omitted messages and icons on belongs-to validations

While following http://offirgolan.github.io/ember-cp-validations/docs/classes/Belongs%20To.html with regular objects (no ember data) i found that although the validations of a child are correctly executed the form element does not display error messages and icons...

These are correctly updated in my view as I type in the field

{{get model 'validations.attrs.testAddress.isValid'}}<br>
{{get model 'validations.attrs.testAddress.messages'}}<br>
{{#bs-form formLayout="vertical" model=model action="submit" disabled=isProcessing}}

    {{bs-form-element controlType="input" placeholder="city" label="City"
                      property="testAddress.populatedPlace"
                      disabled=isProcessing showValidation=true}}

But bs-form-element shows no icons and warning...

Not sure if it is an issue with bs-bootstrap cp-validations or this bridge...

Feature Request: Integrate with ember-validated-form-buffer

Hi,

I'm not sure if this is a problem with ember-bootstrap itself or this integration plugin...
I'm using the plugin with the form-buffer https://github.com/simplabs/ember-validated-form-buffer plugin since i want to declare validations on controllers.
It's working pretty well, except that {{bs-form doesnt seem to get when the form is actually valid, thus preventing the onSubmit action being fired.

It was possible to use it with a little workaround like the following, however i would prefer using the normal onSubmit form flag with it :-)

controller:

import Ember from 'ember';
const {inject: {service}, Controller} = Ember;
import {validator, buildValidations} from 'ember-cp-validations';
import formBufferProperty from 'ember-validated-form-buffer';


const Validations = buildValidations({
  username: [
    validator('presence', true),
    validator('length', {
      min: 3,
      max: 30
    }),
    validator('format', {
      regex: /^[^ "'<>]+$/,
      message: 'Bitte verzichte auf folgende Zeichen in deinem Namen: "\'>< und halt Leerzeichen nä! '
    })
  ],

  email: [
    validator('presence', true),
    validator('format', {type: 'email'}),
    validator('length', {
      min: 10,
      max: 30
    })
  ],
  password1: [
    validator('presence', true),
    validator('length', {
      min: 6,
      max: 30
    }),
    validator('format', {
      regex: /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{3,27}$/,
      message: 'Password must include at least one upper case letter, one lower case letter, and a number'
    })
  ],
  password2: [
    validator('presence', true),
    validator('confirmation', {
      on: 'password1',
      message: '{description} do not match',
      description: 'Passwords'
    })
  ]
})


export default Controller.extend({
  data: formBufferProperty('model', Validations),

  actions: {

    reset() {
      this.get('data').discardBufferedChanges()
    },

    register(){
      this.get('data').applyBufferedChanges()
      const model = this.get('model')
      Ember.Logger.debug('Registriere Model', model)
      this.set('confirmationMessage', null)
      this.set('errorMessage', null)
      model.save().then(s => {
        const success = s.get('success')
        this.set('confirmationMessage', success)
        model.rollbackAttributes()
        model.unloadRecord()
      }).catch(e => {
        this.set('errorMessage', e)
      })
    }

  }
});

template:

<div>
  <p>komm ran! <em>wir brauchen nur so paar daten</em>:</p>
  {{#bs-form model=data as |form|}}
    {{form.element controlType="email" label="becherMail" placeholder="Email" property="email" required=true}}
    {{form.element controlType="text" label="becherAlias" placeholder="Username" property="username" required=true}}
    {{form.element controlType="password" label="becherGeheimnis" placeholder="Password" property="password1"
                   required=true}}
    {{form.element controlType="password" label="becherGeheimnis (zur Sicherheit nochmal..)" placeholder="Password"
                   property="password2" required=true}}
    {{bs-button disabled=data.validations.isInvalid type="primary" defaultText="registierMir"
                icon="glyphicon glyphicon-hand-right" onClick=(action "register")}}
  {{/bs-form}}
  {{#if errorMessage}}
    <div class="alert alert-danger">
      <p>
        <strong>hat nich geklappt man:</strong> <code>{{errorMessage}}</code>
      </p>
    </div>
  {{/if}}
  {{#if confirmationMessage}}
    <div class="alert alert-success">
      <p>
        <strong>hat geklappt man:</strong> <code>{{confirmationMessage}}</code>
      </p>
    </div>
  {{/if}}
</div>

best regards
daniel

asynchronous validations

First, please let me express my gratitude for such a quick response to my question regarding bootstrap <-> cp-validations compatibility. Appreciated.

As I said earlier, the solution seems to work for the most part.

I have a question though. Perhaps it is just not possible.

I have a form with asynchronous validation. While the promised is being resolved, the form show the element as passing the validation. Is this something that you could easily add to this project or should that be functionality of bs-bootstrap?

Documentation issues for v2.0.x

Thank you for the update to this add-on and for ember-bootstrap in general. However, while updating my app I noticed two small issues with the documentation:

  1. The example on the README seems to be for ember-bootstrap-changeset-validations as it uses the changeset helper.
  2. Version 1.x had a nice feature that in certain cases when the cp-validation included presence: true, then it would mark the form element as required (see this line). Given that this seem to not be the case anymore, I think it should have been documented as a breaking change; albeit it would be nice to have this feature back.

Example of how to use with bs-form-group

    {{#bs-form-group validation='???'}}
        <label class = "control-label">Title</label>
        {{bs-input type="text" value=model.title}}
    {{/bs-form-group}}

What should the value of validation be here?

Properties with more then 1 validation not set

Validations performed, no icon nor color for validation with more then one 'assertion'.

https://www.dropbox.com/s/aoy571hh1z3ym7k/Screenshot%202016-03-18%2020.49.04.png?dl=0

const Validations = buildValidations({
  displayName: {
    debounce: 280,
    validators: [
      validator('presence', {presence: true})
    ]
  },
  emailAddress: {
    debounce: 280,
    validators: [
      validator('presence', {presence: true}),
      validator('auth/user/email-address-is-registered', {
        allowBlank: false,
          /* source http://emailregex.com */
        regex : /^[-a-z0-9~!$%^&*_=+}{\'?]+(\.[-a-z0-9~!$%^&*_=+}{\'?]+)*@([a-z0-9_][-a-z0-9_]*(\.[-a-z0-9_]+)*\.(aero|arpa|biz|com|coop|edu|gov|info|int|mil|museum|name|net|org|pro|travel|mobi|[a-z][a-z])|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,5})?$/i
      })
    ]
  },
  password: {
    debounce: 280,
    validators: [
      validator('presence', {presence: true}),
      validator('auth/user/password-strength')
    ]
  },
  passwordConfirmation: {
    debounce: 280,
    validators: [
      validator('presence', {presence: true}),
      validator('confirmation', {
        on: 'password',
        message: 'Passwords do not match'
      })
    ]
  }
});

export default Ember.Object.extend(Validations, {
  displayName: '',
  emailAddress: '',
  password: '',
  passwordConfirmation: ''
});

Models with calculated presence are always required

I have a model with validations similar to this:

  phone: [
    validator('presence', {
      presence() {
        var requirePhone = this.get('model.requirePhone');
        return requirePhone ? true : undefined;
      },
      dependentKeys: ['requirePhone']
    }),
  ],

This results in the computed required attribute always being true, since _attrValidations.options.presence.presence contains the function used to calculate presence, which is treated as true by computed.and.

I am currently doing to following in my apps bs-form-element component to override the required attribute to call the presence function if it exists:

import Ember from 'ember';
import BsFormElement from 'ember-bootstrap-cp-validations/components/bs-form-element';

const {
  computed,
  defineProperty,
  get,
  typeOf
} = Ember;

export default BsFormElement.extend({

  setupValidations() {
    this._super(...arguments);

    let presence = this.get('_attrValidations.options.presence');
    if ( presence && typeOf(get(presence, 'presence')) === 'function' ) {
      let dependentKeys = get(presence, 'dependentKeys');
      defineProperty(this, 'required', 
        computed(...dependentKeys, '_attrValidations.options.presence.presence', 'notDisabled', function () {
          if ( !this.get('notDisabled') ) {
            return false;
          }
          let presence = this.get('_attrValidations.options.presence.presence');
          return typeOf(presence) === 'function' ? presence.apply(this) : presence;
        })
      );
    } 
    else {
      defineProperty(this, 'required', computed.and('_attrValidations.options.presence.presence', 'notDisabled'));
    }
  },

`novalidation=true` by default

The browser's native validation support will disrupt the addons validations, so novalidation=true should be set by default on the bs-form component.

Probably better in a major version bump?

Maintenance / Repo ownership

Hey @offirgolan, it's been a while, hope you are all well! 😀

I have used my OSS friday to update things here, as this addon hasn't been touched for a while (3 years 😱). Wanted to drop support for old versions, make sure everything run with the latest ember-bootstrap, and some general maintenance stuff.

In the latter category I wanted to move CI to Github Actions (#25), but it seems the Travis CI check (which I wanted to replace) is set up in this repo to be required:

image

Thing is I don't have the required privileges here to change these settings. That brings up the question - given that as I said maintenance of this addon was a bit behind - whether you actually are still interested in ownership of this repo, and the maintenance burden related to it? :)

So either giving me administration rights here would make me able to continue maintaining this without bothering you. Or if you are not at all interesting in keeping this repo, would you consider transferring ownership to me?

Server side validations

I'm relying on this addon to take advantage of the DS.Error integration provided by ember-cp-validations (no client side validation). However I'm facing the following issue: text fields losing focus automatically turn green as if validation passed. I'm having a hard time figuring out where and what needs tweaking so that the addon only "kicks in" when errors actually get returned from the server?

Support display of belongs-to validation messages

In the interests of sharing. The following setupValidations() method works to enable you to render nested form property validations (I'm sure some js ninjas out there can cleanup the string manipulation)!

\\file: app/components/bs-form/element.js
setupValidations() {
  let propertyPath = get(this, 'property');
  let modelPath = "model";
  let propertyArray = propertyPath.split('.');

  if (propertyArray.length > 1) {
    propertyPath = propertyArray.pop();
    modelPath = `model.${propertyArray.join('.')}`
  }

  defineProperty(this, '_attrValidations', readOnly(`${modelPath}.validations.attrs.${propertyPath}`)); 
  defineProperty(this, 'errors', readOnly('_attrValidations.messages'));
  defineProperty(this, 'warnings', readOnly('_attrValidations.warningMessages'));
}

RFC: partial model validation

To be able to partially validate models, I have added a file with this content - which overrides the BsForm provided by this package.

Setting `{{bs-form validationOptions=(hash on=(array 'fieldPath') excludes=(array 'otherPath')) enables this.

I'm not sure about model.set('validations.errors', validations.get('errors')); but model.get('isTruelyValid') seems to work.

import ObjectProxy from '@ember/object/proxy';
import { Promise as EmberPromise } from 'rsvp';
import BsForm from 'ember-bootstrap/components/bs-form';

export default BsForm.extend({
  validationOptions: {},
  validate(model) {
    return new EmberPromise((resolve, reject) => {
      let m = model;

      if (model instanceof ObjectProxy) {
        m = model.get('content');
      }

      m.validate(this.get('validationOptions')).then(
        validations => {
          model.set('validations.errors', validations.get('errors'));
          model.get('validations.isTruelyValid') ? resolve() : reject();
        },
        error => {
          reject();
        }
      );
    });
  }
});

Thoughts? think it might be good to create a PR?

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.