Giter Site home page Giter Site logo

adfinis / ember-validated-form Goto Github PK

View Code? Open in Web Editor NEW
68.0 15.0 32.0 31.83 MB

Easily create forms with client side validations.

Home Page: https://adfinis.github.io/ember-validated-form

License: MIT License

JavaScript 78.06% HTML 1.73% CSS 0.25% Handlebars 19.77% Shell 0.19%
ember-addon validations ember-changeset forms

ember-validated-form's Introduction

ember-validated-form

npm version Ember Observer Score Test Code Style: Prettier

Easily create forms with client side validations.

gif

Want to try it yourself? View the docs here.

Contributing

Bug reports, suggestions and pull requests are always welcome!

See the Contributing guide for details.

License

This project is licensed under the MIT License.

ember-validated-form's People

Contributors

andreabettich avatar anehx avatar brandensilva avatar czosel avatar dependabot-preview[bot] avatar dependabot[bot] avatar derrabauke avatar ember-tomster avatar feanor07 avatar fkm avatar fkm-adfinis avatar jacob-financeit avatar kalda341 avatar kimroen avatar lesyk-lesyk avatar makepanic avatar marissamac avatar nmccready avatar omairvaiyani avatar przywartya avatar psteininger avatar semantic-release-bot avatar sliverc avatar staffe avatar stephanh90 avatar steverhoades avatar topaxi avatar toumbask avatar velrest avatar yelinz 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

Watchers

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

ember-validated-form's Issues

Multiple forms with a same named field on one page cause error

If you use multiple forms which have a same named field, the addon causes an error:

Error: Assertion Failed: Attempted to register a view with an id already in use: firstName
    at assert (ember.debug.js:5982)
    at Object.assert (ember.debug.js:17733)
    at InteractiveRenderer.register (ember.debug.js:12303)
    at Object.enter (ember.debug.js:42975)
    at Class._transitionTo (ember.debug.js:41593)
    at CurlyComponentManager.didCreate (ember.debug.js:13040)
    at Environment.commit (ember.debug.js:51491)
    at Environment.commit (ember.debug.js:9604)
    at InteractiveRenderer._renderRoots (ember.debug.js:12431)
    at InteractiveRenderer._renderRootsTransaction (ember.debug.js:12460)

This is caused because the ID of the input helper is equal to the name, which is used as target for the label. To fix this you could generate some kind of unique string to use as ID.

Demo: https://ember-twiddle.com/ef75748f2f62b0b793c7bf5e06557ef8 (Error is visible in the console)

Accessing form data in action

I am converting a component to use ember-validated-form. The validation is working, it flags if no content is present, and it allows calling the "submit" action if content is present.

When I try to access the entered form value (with this.get('name') ) I get undefined.

Is there a different convention for accessing form data?

Here is my component.js file:

  • "addShow" is the old action
  • "submit" is the new, ember-validated-form action.
import Ember from 'ember';
import UserValidations from '../validations/add-show-input';

export default Ember.Component.extend({

  UserValidations: UserValidations,

  actions: {
    addShow() {
      const model = this.get('model');
      const router = this.get('router');  // Provided by initializer
      const component = this;

      let newShow = model.store.createRecord('show', {
        name: this.get('name'),
      });
      return newShow.save().then(function () {
        component.set('name', '');  // Zero out field
        router.transitionTo('show', newShow);
      });
    },

    submit() {
      let showName = this.get('name');
      alert(showName);
    },

  }
});

Full code is available at https://github.com/dale42/showtime/tree/ember-validated-form-impl

Component:

Component is used in this template:

How to make date or calendar inputs?

Hi!, i want to create a form with on date field, but i don't understand how to represent the field to show a date or allow to popup a calendar. I used before an addon called ember-pikaday, but seems to be impossible to integrate in a form made with ember-validated-form.

any advice?

Add possibility to customize checkbox and radio style

Hi,
Thanks for the great addon.

I was trying to customize the checkbox/radio input style but found it to be impossible.

Usually one hides the real input element and uses an adjacent sibling combinator to create a fake checkbox.
Something like input[type=checkbox]:checked + div is used to control the fake checkbox style.
Sadly it's not possible as this addon generates a label that wraps the input and its label text:

<label>
  <input type=checkbox/>
  {{label}}
</label>

The most backwards compatible way to solve this issue would be to wrap the label in an unstyled element:

<label>
  <input type=checkbox/>
  <span>{{label}}</span>
</label>

That way one could introduce a fake checkbox with [type=checkbox] + span:before and also style the label once the checkbox is checked.

Any thoughts on this? If the proposed solution is fine, I could open a PR.

Custom layout for input

Hey guys!

I am creating a custom input with another input element inside so I can customize the layout. The problem is that with every change, the value is updated with a jQuery event instead of the actual value.

Please check this twiddle.

Can you please help me figuring out what I'm doing wrong? Is there a proper way of doing this?

Thanks in advance

retrieving field value before form is validated

Hello,

Thanks for this lovely plugin. However, we are facing a major issue which is holding us back. I have a form where I need to observe a field within a form (quantity) and update a field total price as the field is changed.

How to access the value before the form is validated?

Thanks

Hide save button based on boolean

This would be straightforward to do with a real button like {{if notEditing 'hidden'}}, but is there a way to do it with this automatically generated button?

support for custom component usage should be improved

Custom component usage seems to be needing some improvement; because the addon already provides label and error showing for built-in types such as select, text-input, etc. However; when a developer wants to use a custom component he is not able to give the same look&feel (css settings, etc.) like the built-in components. A proper yielding of necessary attributes from validated-input.hbs should enable better custom component leveraging and enable usage of validated-input in block form; which gives quite a lot of power to the developers.

Stricter eslint config

It would be nice to enforce a little more code style rules beyond eslint:recommended (Example: semi).

Unneeded runtime dependencies

The following runtime dependencies are not, as far as I can tell, actually needed at runtime:

  • bower
  • ember-changeset
  • ember-changeset-validations

I think bower can just be removed entirely.

The addon is built to use ember-changeset and ember-changeset-validations, but is usable without them, so putting them in the runtime dependencies makes the addon less lightweight, and requires maintenance to keep up with the latest version (e.g. #69).

I propose that we move them from dependencies to devDependencies and then either:

  1. Add info to the documentation about installing them
  2. Install them into apps via a blueprint

I guess this would require a major version bump as it would be a breaking change to anybody using ember-changeset or ember-changeset-validations that hasn't put them in their own package.json.

Thoughts? I'm happy to open a PR removing bower and implementing either of the options above.

Pressing `enter` to submit form behaves strangely when using custom inputs

I have a form that has a custom input and when using the enter key to submit the form I get some weird results.

First time pressing enter when focused on the Reason input my custom input's value seems to get cleared out and the form does not submit.

Pressing enter again submits the form with the custom input's value which was selected before pressing the enter key the first time.

If I submit the form by clicking on the submit button the form behaves as expected.

If I remove the custom input and press enter to submit the form it behaves as expected.

{{#f.input name='serviceable' class="serviceable" as |fi|}}
  {{#unless hideServiceable}}
    <div class="required field">
      <label>Resource</label>
      {{serviceable-selector
              selectedServiceable=fi.value
              onSelect=(action 'setServiceable' fi.update)
              onClear=(action 'clearServiceable')
              handleScan=(action 'handleScan' fi.update)
       }}
      </div>
    {{else}}
  {{/unless}}
{{/f.input}}

{{#f.input name='name' as |fi|}}
  <div class="required field">
    <label>Reason</label>
    <input type="text" value={{fi.value}} onchange={{action fi.update value="target.value"}} autocomplete="off">
  </div>
{{/f.input}}
{{f.submit label=(t (if serviceOrder.isNew 'saveAndStartWork' 'update')) disabled=f.loading}}

Autofocus on didRender

Currently, input autofocus only occurs on the DOM ready event.

Adding something like the following to validated-form would ensure every time the form is rendered, autofocus is respected.

didRender() {
  this._super(...arguments);
  this.focusOnRender();
},

focusOnRender() {
  let $focusInput = this.$().find('[autofocus]');
  if ($focusInput.length) { $focusInput.focus(); }
}

Can submit a PR. Also happy to implement in vanilla JS code to comply with future PR emberjs/rfcs#294.

Use model properties to populate dropdowns

Can this be possible, instead of having to hard code the list of dropdown options? For example I have a book model, which has an author property, and each of these has an API endpoint so there would be a list of authors at the author endpoint. Is it possible to use these to populate an author dropdown in order to update the book model's author property?

Best way to create inline forms with hasMany relationship?

I just started using your form extensions and also haven't used ember-changeset before. I'm currently struggling with figuring out the best way to have inline forms.

We have a candidate model which has one or more jobs. The form should look like this

- input: candidate.firstName
-- input: candidate.jobs[0].title
-- input: candidate.jobs[1].title
...
- Submit button

So I want to display multiple models from a hasMany relationship but with only a single submit button at the end of the form.

I did a quick test if nesting the forms would work like this

{{#validated-form
   model=(changeset model CandidateValidations)
  on-submit    = (action "submit")
  submit-label = 'Save' as |f|}}

{{f.input name="firstName"}}

    {{#validated-form tagName="div"
	model=(changeset model.jobs.firstObject JobValidations)
            as |fi| }}
        {{fi.input name="title"}}
    {{/validated-form}}

{{/validated-form}}

It seems to work fine in a sense the inner and the outer changeset track the changes independently, but the outer changeset is not aware of the changes from the inner.

Now I think I can make it work, when on submit I collect the inner changesets, validate and apply them manually to the models.

But before digging deeper I wanted to ask whether there is a better approach to solve this.

Unable to submit the form

Hi,

When I try to submit the form, I get the following error :

ember.debug.js:16905 TypeError: method.apply is not a function
    at Backburner.join (ember.debug.js:773)
    at Function.run.join (ember.debug.js:21556)
    at ember.debug.js:9478
    at Object.flaggedInstrument (ember.debug.js:17747)
    at ember.debug.js:9477
    at runTaskOrAction (component.js:5)
    at component.js:60
    at tryCatch (ember.debug.js:58165)
    at invokeCallback (ember.debug.js:58177)
    at publish (ember.debug.js:58148)

Also, I see that the model that is being set inside the form, is not present outside anywhere. That is, if I try to get using this.get('model') which was the same that was given in {{validated-form}}, it is empty!!!

Please guide me! Thanks in advance!!

Add more css customisation options form semantic-ui

Hi!, i want to use semantic-ui with this addon, but i have some issues with a lack of some
css customisation options.

For example, i need a css customisation option to set a class name to the form element, and
wrap the field input to show errors.

I make a change in templates to tests this changes, but i wish to find another way to prevent a fork:

https://github.com/hugoruscitti/ember-validated-form/commit/208ca230e53851bf414d33b056b27e5a26144328

any advice ?

Update an already existing model using validated-form

Hi @czosel & Others,

I am getting the model thro the route's model hook. I want to validate an already filled form, retrieved from the server. And, save it using the validated-form.

I made an effort to do it, but what happens is, even if a model is present, validated-form is creating a new empty object for it. So, the changes aren't reflecting in the actual model.

Is there a solution to achieve what I am trying?

Please check this Twiddle

Many thanks in advance!

Prettier integration

I think the source of this addon is formatted with Prettier pretty consistently now - we should probably add a "styled with Prettier" badge to the README and enforce it in CI.

@anehx

Custom component not showing error until save is clicked

Hi @czosel & others!

I have a form in which I have few custom components (power-select, power-select-multiple, etc.) and validated-form fields.

When I focus on a validated-form's field, and focusout, without value, it shows as a validation error.

But, when I focus on a custom component & focusout without value, it doesn't.

However, if I click on Save, model.validate() is invoked, and thus, the validation error(s) are thrown.

My expectation : Even with custom components, I want to see validation error when I focus out.

Please see this twiddle, for the issue reproduction.
https://ember-twiddle.com/7693dda4ebdebcda2065c0b3087011c5?openFiles=templates.application.hbs%2C

Is it possible to get this done? Please help me with this.

Improve a11y

We should include aria tags (like aria-describedby and aria-invalid).

Select multiple and selectedValue in dropdowns

I'm making a dropdown which is populated with data from a model, that can be updated with this edit form. The model might have two properties, eg, the book model might have two authors, so when the book model is being edited, the author dropdown should be populated with the list of all possible authors, with the two existed authors preselected, and you should have the ability to select more. Could this be possible?

Disabling input (text) causes the value to be missing

I want to display the text value in an input field, but disable edit. I assumed that setting disabled=true would result in this, but it causes the value to be empty - it does however disable the input element as expected.

Anyone got this issue?

Make setDirty more clever

Right now setDirty always sets the dirty property to true.
We could make it more clever to only dirty the form if the changeset isDirty is true.

This also helps to prevents validating the form when removing focus of a form that uses autofocus to focus the first input element.

If you're fine with this solution, I could open a PR.

RFC: API redesign

Many users of this addon had problem using it with their favorite CSS framework. The HTML output is currently too inflexible. To change this we propose the following new API for the validated-input component. Since this will break current integrations we'd like to get early feedback to this change.

The new API could look something like this:

{{#validated-form model=(changeset model validations) on-submit=(perform submit) as |f|}}
  {{f.input renderComponent=(component 'my-text-input') name='code' label='Security code'}}

  {{f.input type='text' name='name' label='Name'}}
{{/validated-form}}

{{! /templates/components/my-text-input.hbs }}

{{@labelComponent}}

<input
  id={{@inputId}}
  type="text"
  class="somefancyclass {{if @isInvalid 'error-class'}} {{if @isValid 'valid-class'}}"
  value={{@value}}
  name={{@name}}
  oninput={{action @update value="target.value"}}
  onblur={{action @setDirty}}
>

{{@hintComponent}}
{{@errorComponent}}

New features

  • Full control over HTML output of your inputs
  • Themes: Bootstrap and UIkit to start
  • Global configuration of a default theme
  • errorComponent to customize the errors
  • hintComponent to customize the hints

Optional features

  • Option to map custom renderComponent to types
  • Set theme on form and input as well
  • Globally configure custom components (also per type)
  • Treeshaking of unused themes

Breaking changes

  • config.css will be dropped in favor of theming
  • Support for block style custom components will be dropped

Related issues

All feedback is very welcome!

CC: @czosel @bendemboski @jacob-financeit @makepanic @kimroen @omairvaiyani

Configuration in config/environment.js not working?

The custom css classes applied to the form and other elements is not being applied. My environment.js file is pretty basic. I am using a sass compiler instead of plain css, but doesn't seem like this would impact adding classes to form elements at runtime.
Is there anything I am doing incorrectly here?

module.exports = function (environment) {
  let ENV = {
    modulePrefix: 'tourney-admin',
    environment,
    rootURL: '/',
    locationType: 'auto',
    EmberENV: {
      FEATURES: {
        // Here you can enable experimental features on an ember canary build
        // e.g. 'with-controller': true
      },
      EXTEND_PROTOTYPES: {
        // Prevent Ember Data from overriding Date.parse.
        Date: false
      }
    },

    APP: {
      // Here you can pass flags/options to your application instance
      // when it is created
    },


    /**
     * Font Awesome Config
     */
    fontawesome: {
      icons: {
        'free-solid-svg-icons': 'all'
      }
    },
    'ember-validated-form': {
      css: {
        // bootstrap classes
        group: "form-group",
        radio: "radio",
        control: "form-control",
        label: "col-form-label",
        help: "small form-text text-danger",
        hint: "small form-text text-muted",
        checkbox: "checkbox",
        button: "btn btn-default",
        submit: "btn btn-primary",
        loading: "loading",
        valid: "is-valid",
        error: "is-invalid"
      }
    }

  };

  if (environment === 'development') {

    // ENV.APP.LOG_RESOLVER = true;
    // ENV.APP.LOG_ACTIVE_GENERATION = true;
    // ENV.APP.LOG_TRANSITIONS = true;
    // ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
    // ENV.APP.LOG_VIEW_LOOKUPS = true;
  }

  if (environment === 'test') {
    // Testem prefers this...
    ENV.locationType = 'none';

    // keep test console output quieter
    ENV.APP.LOG_ACTIVE_GENERATION = false;
    ENV.APP.LOG_VIEW_LOOKUPS = false;

    ENV.APP.rootElement = '#ember-testing';
    ENV.APP.autoboot = false;
  }

  if (environment === 'production') {
    // here you can enable a production-specific feature
  }

  return ENV;
};

Latest version of the dependencies not added here yet

Hi @czosel,

Currently in ember-validated-form we do not have the facility to use nested models, as ember-changeset didn't have. But few days back, ember-changeset has updated their package with this one merged to their code. Can you please update your ember-changeset version so that I will be able to utilize this in my application? Also, please update README with the how-tos as well. Thank you :)

Bootstrap 4 support

Hi guys!

Very nice job with this addon!
Is there a way to use this with bootstrap 4?

Thanks,

Autosuggest in dropdowns

Is it possible to have a regex type search in the top part of a select input to quickly select one of the options in a dropdown? We have a dropdown with maybe 200 entries. Thanks for the addon!

Removing radio input value made it impossible to select radio inputs in testing

4edbbd4 moved away from one-way-radio.

It looks like it also removed the value attribute on radio inputs.
This means before it would look something like this:

<input type="radio" value="public" .../>

And after the commit:

<input type="radio" .../>

This makes it impossible to find the correct radio input during testing.
The easiest way to add it back is to simply add the option key as value = {{option.key}} to each radio input.

If this is ok, I can open a PR that adds it back.

Fastboot issue?

There was an error running your app in fastboot. More info about the error:
Error: Assertion Failed: Underlying object for changeset is missing.

I followed the directions pretty closely. I believe that I have everything configured correctly and I am getting this error-which does not appear prior to installing the add-on.

Did I somehow miss a step for Fastboot?

Please help as this is holding me up right now.

Submitting the form refreshes the page

For some reason, despite setting an action on the forms on-submit, clicking on {{f.submit}} refreshes my browser, as if its posting the form. As a workaround I've set tagName="div" on my {{#validated-form}} block, and set the action directly on my submit button. But this has its own set of problems; specifically, the validations do not work when I click the submit button, as it no longer goes through this component's submit pathway. Any help?

Show version in demo

We should display the addon version in the demo somehow to make sure we have the latest version deployed.

Checkbox labels aren't wrapped in a span anymore

I think #95 introduced a regression where checkbox elements don't use a span wrapped label anymore.

https://github.com/adfinis-sygroup/ember-validated-form/pull/95/files#diff-3fdbc85ba77b90bb068fe83da64dee87L85 removed wrapping the checkbox label in a span by introducing a validated-label that is simply echoing the {{label}}.

I think it's my fault for not adding a test that checks that checkbox labels are also wrapped in a span.

There's probably a similar issue where validated-label isn't used for radio inputs. Meaning you can't customize the label there.

There are various possible options to solve this:

  • use validated-label for all label usages in validated-input
  • add span wrapping to validated-label, which means all validated-labels will change or
  • add wrapped attribute to validated-label which will be set to true for uses in checkbox or radio inputs

I can open a PR if we find a solution

Integrating with Other components

Hi,

I am using power-select and power-select-multiple with validated-form like :

model ->

{
obj: {
id: null,
name: null
}
}

{{#f.input name='obj'as |fi|}}
{{#power-select-multiple
options=options
searchField='name'
onchange=fi.update
placeholder='Select'
selected obj as |o|}}
{{o.name}}
{{/power-select-multiple}}
{{/f.input}}

With this, I am able to see the dropdown, but selecting a value doesn't render the selected value to the dropdown. Also, I am not able to search using name.

Kindly give some guidance.

Thanks in advance!

Is there something like integration with pure HTML ?

Let's say I have the following form, How I make it work as expected with this library ? or How to write it in a way that provides the same HTML?

My problem that i cannot make the inline validation work or fetching the value of the typed name through controller. However everything works as expected if i used the library syntax but cannot get the same UI as i cannot provide the same classes to these tags for example 'input'

{{#validated-form class="form-horizontal form-label-left" model = (changeset model TodoValidations) on-submit = (action "submit") as |f|}}
    <div class="form-group">
        <label class="control-label col-md-3 col-sm-3 col-xs-12" for="name">Name <span class="required">*</span></label>
        <div name='name' class="col-md-6 col-sm-6 col-xs-12">
            <input type="text" name="name" id="name-input-name" required="required" class="form-control col-md-7 col-xs-12">
        </div>
    </div>
    <div class="ln_solid"></div>
    <div class="form-group">
        <div class="col-md-6 col-sm-6 col-xs-12 col-md-offset-3">
            <button class="btn btn-primary" type="reset">Reset</button>
            {{f.submit label="Save" class="btn btn-success"}}
        </div>
    </div>
{{/validated-form}}

Div tag getting attached to every f.input

Hi,
I am using validated-form for validating my page. I see that for every f.input tag, I get a div attached to it. which disturbs my css.

Is there any way in which I can remove the div tags?

Ember 2.13 Fails with helper validated-form not found.

$ ember install ember-validated-form
NPM: Installed ember-validated-form
Installed addon package.

controller.js

import Ember from 'ember';
import {
  validatePresence
} from 'ember-changeset-validations/validators';

export default Ember.Controller.extend({
  validators: {
    name: [validatePresence(true)]
  },

  actions: {
    submit() {

    }
  }
});

template.hbs

{{#validated-form
  model       = (changeset model validators)
  on-submit   = (action "submit")
  submit-label = 'Save' as |f|}}

  {{f.input label="Name" name="name"}}

  {{/validated-form}}

Results in:

Assertion Failed: A component or helper named "validated-form" could not be found

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.