Installations
npm install ampersand-input-view
Developer Guide
Typescript
No
Module System
CommonJS
Node Version
6.2.0
NPM Version
3.8.9
Score
66.6
Supply Chain
58.7
Quality
80.1
Maintenance
100
Vulnerability
97.9
License
Releases
Unable to fetch releases
Contributors
Unable to fetch Contributors
Languages
JavaScript (100%)
Love this project? Help keep it running — sponsor us today! 🚀
Developer
ampersandjs
Download Statistics
Total Downloads
234,511
Last Day
33
Last Week
147
Last Month
680
Last Year
5,936
GitHub Statistics
17 Stars
174 Commits
19 Forks
13 Watching
4 Branches
28 Contributors
Bundle Size
77.76 kB
Minified
23.26 kB
Minified + Gzipped
Package Meta Information
Latest Version
7.0.0
Package Id
ampersand-input-view@7.0.0
Size
3.52 kB
NPM Version
3.8.9
Node Version
6.2.0
Total Downloads
Cumulative downloads
Total Downloads
234,511
Last day
73.7%
33
Compared to previous day
Last week
-40.5%
147
Compared to previous week
Last month
34.7%
680
Compared to previous month
Last year
-21.8%
5,936
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
ampersand-input-view
Lead Maintainer: Christopher Dieringer (@cdaringe)
Purpose
A view module for intelligently rendering and validating input. Works well with ampersand-form-view.
It does the following:
- Automatically shows/hides error messages based on tests
- Will not show error messages pre-submit, or if it's never had a valid value. This lets people tab-through a form without triggering a bunch of error messages.
- Live-validates, to always report if in valid state. But only shows messages when sane to do so.
- Only shows first failed message. Then, as the user corrects, updates and validates against all tests, showing appropriate message, until all tests pass.
It's built on ampersand-view, so you can use it with extend
as expected.
install
npm install ampersand-input-view
example
1var FormView = require('ampersand-form-view'); 2var InputView = require('ampersand-input-view'); 3 4 5module.exports = FormView.extend({ 6 fields: function () { 7 return [ 8 new InputView({ 9 label: 'Address', 10 name: 'address', 11 value: this.model.address || '', 12 required: false, 13 placeholder: '2000 Avenue of the Stars, Los Angeles CA', 14 parent: this 15 }) 16 ]; 17 } 18});
API Reference
extend AmpersandInputView.extend({ })
Since this view is based on ampersand-state, it can be extended in the same way.
To create an InputView
class of your own, you extend AmpersandInputView
and provide instance properties and options for your class. Here, you will typically pass any properties (props
, session
, and derived
) of your state class, and any methods to be attached to instances of your class.
Note: If you want to add initialize()
, remember that it's overriding InputView's own initialize()
. Thus, you should call the parent's initialize()
manually:
1var AmpersandInputView = require('ampersand-input-view'); 2 3var MyCustomInput = AmpersandInputView.extend({ 4 initialize: function () { 5 // call its parent's initialize manually 6 AmpersandInputView.prototype.initialize.apply(this, arguments); 7 8 // do whatever else you need to do on init here 9 } 10});
constructor/initialize new AmpersandInputView([opts])
When creating an instance of an InputView
, you can pass in the initial values of the attributes which will be set
on the state. Unless extraProperties
is set to allow
, you will need to have defined these attributes in props
or session
.
opts
tests
(default:[]
): test function to run on input (more below).name
: the input'sname
attribute's value. Used when reporting to parent form.type
(default:'text'
): input type to use, can be any valid HTML5 input type.value
: initial value for the<input>
.template
: a custom template to use (see 'template' section, below, for more).placeholder
: (optional) "placeholder text" for the input.el
: (optional) element if you want to render it into a specific exisiting element pass it on initialization.required
(default:true
): whether this field is required or not.readonly
(default:false
): whether this field is read only or not.autofocus
(default:false
): whether this field automatically gets focus on page load or not.requiredMessage
(default:'This field is required'
): message to use if required and empty.validClass
(default:'input-valid'
): class to apply to input if valid (see below for customizing where this is applied).invalidClass
(default:'input-invalid'
): class to apply to input if invalid (see below for customizing where this is applied).parent
: a View instance to use as theparent
for this input. If your InputView is in a FormView, this is automatically set for you.beforeSubmit
: function called by ampersand-form-view during submit. By default this runs the tests and displays error messages.tabindex
(default:0
): Specify the tab index number for your field (integer).
render inputView.render()
Renders the inputView. This is called automatically if your inputView is used within a parent ampersand-form-view.
template inputView.template
This can either be customized by using extend
, or by passing in a template
on instantiation.
It can be a function that returns a string of HTML or DOM element--or just an plain old HTML string.
But whatever it is, the resulting HTML should contain the following hooks:
- an
<input>
or<textarea>
element - an element with a
data-hook="label"
attribute - an element with a
data-hook="message-container"
attribute (this we'll show/hide) - an element with a
data-hook="message-text"
attribute (where message text goes for error)
Creating a new class:
1// creating a custom input that has an alternate template 2var CustomInput = AmpersandInputView.extend({ 3 template: [ 4 '<label>', 5 '<input class="form-input">', 6 '<span data-hook="label"></span>', 7 '<div data-hook="message-container" class="message message-below message-error">', 8 '<p data-hook="message-text"></p>', 9 '</div>', 10 '</label>' 11 ].join('') 12}); 13 14// Then any instances of that would have it 15var myCustomInput = new CustomInput();
Setting the template when instantiating it:
// Or you can also pass it in when creating the instance
var myInput = new AmpersandInputView({
template: myCustomTemplateStringOrFunction
});
value new AmpersandInputView({ value: 'something' })
If you pass value
on instantiation, it will be set on the <input>
element (and also tracked as startingValue
).
This is also the value that will be reverted to if we call .reset()
on the input.
1var myInput = new AmpersandInputView({ 2 name: 'company name', 3 value: '&yet' 4}); 5myInput.render(); 6console.log(myInput.input.value); //=> '&yet' 7 8myInput.setValue('something else'); 9console.log(myInput.input.value); //=> 'something else' 10myInput.setValue('something else'); 11myInput.reset(); 12console.log(myInput.input.value); //=> '&yet'
Customizing the view
Custom calculated output value
If you need to decouple what the user puts into the form from the resulting value, you can do that by overriding the value
derived property.
For example, consider a validated address input. You may have a single text input for address, which you can attempt to match to a real known address with an API call. So, you have a single <input>
, but you want the inputView's value
to be an object returned from that API.
Do it by overriding the value
derived property as follows:
1var VerifiedAddressInput = AmpersandInputView.extend({ 2 initialize: function () { 3 // call parent constructor 4 AmpersandInputView.prototype.initialize.apply(this, arguments); 5 6 // listen for changes to input value 7 this.on('change:inputValue', this.validateAddress, this); 8 }, 9 props: { 10 verifiedAddress: { 11 type: 'object' 12 } 13 }, 14 derived: { 15 value: { 16 // in you want it re-calculated 17 // when the user changes input 18 // make it dependent on `inputValue` 19 deps: ['verifiedAddress'], 20 fn: function () { 21 // calculate your value here 22 return this.verifiedAddress; 23 } 24 }, 25 // you may also want to change what 26 // deterines if this field should be 27 // considerd valid. In this case, whether 28 // it has a validated address 29 valid: { 30 deps: ['value'], 31 fn: function () { 32 if (this.verifiedAddress) { 33 return true; 34 } else { 35 return false; 36 } 37 } 38 } 39 }, 40 // run our address verification 41 validateAddress: function () { 42 // validate it against your API (up to you how) 43 validateIt(this.inputValue, function (result) { 44 this.verifiedAddress = result; 45 }); 46 } 47});
Setting valid/invalid classes
By default, validClass
and invalidClass
are set on either the input
or textarea
in the rendered template. This is done via a validityClassSelector
property that is used to find the elements to apply either validClass
or invalidClass
. You can set validityClassSelector
to have this class applied anywhere you need in your rendered template
For instance, this would set the class on the root label instead:
1var CustomInput = InputView.extend({ 2 validityClassSelector: 'label' 3});
And this would set it on the root label and the message element
1var CustomInput = InputView.extend({ 2 validityClassSelector: 'label, [data-hook=message-text]' 3});
tests InputView.extend({ tests: [test functions] });
or new InputView({ tests: [] })
You can provide tests inside extend
, or passed them in for initialize
.
This should be an array of test functions. The test functions will be called with the context of the inputView, and receive the input value
as the argument.
The tests should return an error message if invalid, and return a falsy value otherwise (or, simply not return at all).
1var myInput = new InputView({ 2 name: 'tweet', 3 label: 'Your Tweet', 4 tests: [ 5 function (value) { 6 if (value.length > 140) { 7 return "A tweet can be no more than 140 characters"; 8 } 9 } 10 ] 11});
Note: You can still do required: true
and pass tests. If you do, it will check if it's not empty first, and show the requiredMessage
error if it is.
Remember that the inputView will only show one error per field at a time. This is to minimize annoyance. We don't want to show "this field is required" and every other error if they just left it empty. We just show the first one that fails, then when they go to correct it, it will update to reflect the next failed test (if any).
setValue inputView.setValue([value], [skipValidation|bool])
Setter for value that will fire all appropriate handlers/tests. Can also be done by user input or setting value of input
manually.
Passing true
as second argument will skip validation. This is mainly for internal use.
Setting input.value on non-user input
This module assumes that the value of the input element will be set by the user. This is the only event that can be reliably listened for on an input element. If you have a third-party library (i.e. Bootstrap or jQuery) that is going to be affecting the input value directly you will need to let your model know about the change via setValue
.
1var myInput = new InputView({ 2 name: 'date' 3}); 4myInput.render(); 5document.body.appendChild(myInput.el); 6 7$('[name=address]').datepicker({ 8 onSelect: function (newDate) { 9 myInput.setValue(newDate); 10 } 11});
reset inputView.reset()
Set value to back original value. If you passed a value
when creating the view it will reset to that, otherwise to ''
.
clear inputView.clear()
Sets value to ''
no matter what previous values were.
gotchas
- Some browsers do not always fire a
change
event as expected. In these rare cases, validation may not occur when expected. Validation will occur regardless on form submission, specifically when this field'sbeforeSubmit
executes.
changelog
-
7.0.0
- Upgrade to &-view 10.x (@RickButler #74)
- Add
autofocus
option (@taketwo #73)
-
6.0.0
- Upgrade to &-view 9.x
-
5.1.0
- add
tabindex
- add
-
5.0.0
- Upgrade to &-view 8.x
- Add
readonly
option - dependency and test maintenance
-
4.0.5
- Handle uncaught input value changes beforeSubmit
- Add view convention tests, and update to pass them
-
4.0.0
- Remove
rootElementClass
in favor of a better validityClass selector - Listen to
change
instead ofblur
event - Reset error message state on
clear()
andreset()
- Allow
beforeSubmit
to be defined on initialization
- Remove
-
3.1.0 - Add ampersand-version for version tracking.
-
3.0.0 - Add API reference docs. Add
.clear()
,.reset()
methods. Makevalue
derived property. Fix #21 validity class issue. -
2.1.0 - Can now set
rootElementClass
. Add reset function #15. Allow setting0
as value #17. -
2.0.2 - Make sure templates can be passed in, in constructor.
credits
Created by @HenrikJoreteg.
license
MIT
![Empty State](/_next/static/media/empty.e5fae2e5.png)
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
0 existing vulnerabilities detected
Reason
license file detected
Details
- Info: project has a license file: LICENSE.md:0
- Info: FSF or OSI recognized license: MIT License: LICENSE.md:0
Reason
Found 5/27 approved changesets -- score normalized to 1
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
- Warn: no security policy file detected
- Warn: no security file to analyze
- Warn: no security file to analyze
- Warn: no security file to analyze
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
branch protection not enabled on development/release branches
Details
- Warn: branch protection not enabled for branch 'master'
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 10 are checked with a SAST tool
Score
3.2
/10
Last Scanned on 2025-02-03
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn MoreOther packages similar to ampersand-input-view
ampersand-array-input-view
A view module for intelligently rendering and validating inputs that should produce an array of values. Works well with ampersand-form-view.
ampersand-floatinglabel-input-view
An extended Ampersand.js input view to provide floating labels on input elements
ampersand-filereader-input-view
A view module for returning metadata via callback using browser FileReader.
ampersand-avatar-input-view