Html Form Strategy for univalid module.
Extends univalid-strategy class
You need also install univalid module, it is a core of validation, which manage different strategies.
npm i univalid
npm i univalid-strategy-form
const univalid = require('univalid')();
const UnivalidStrategyForm = require('univalid-strategy-form');
// Base initialize (set strategy)
univalid.setStrategy(
UnivalidStrategyForm({
core: univalid, /* required prop */
$form: '.js-reg-form', /* required prop */
statusConfig: {
targetParent: '.form-group',
targetStatus: '.form__msg'
}
})
);
univalid.on('end:valid', uni => {
console.log(uni.getCommonState, uni.getState);
uni.clearState();
});
<form action="/" method="POST" class="js-reg-form">
<div class="form-group">
<label>Username</label>
<input
name="username"
data-validation="required"
data-f="oL"
data-msg='{"empty":"This Filed empty", "invalid": "This Field Invalid", "filter": "Latin Only", "success": "Is Ok"}'>
<div class="form__msg"></div>
</div>
<div class="form-group">
<label>Lastname</label>
<input
name="lastname"
data-validation
data-f="oC">
<div class="form__msg"></div>
</div>
<div class="form-group">
<label>Email address</label>
<input
name="email"
data-validation="email">
<div class="form__msg"></div>
</div>
</form>
Add to your html form elements (inputs, selects, textarea) 'data-validation=[type]'
In current time supports next types:
- required
- password
- equal - (equal password type)
<div class="form-group">
<label>Username</label>
<input
type="text"
name="username"
class="form-control"
data-validation="required">
<div class="form__msg"></div>
</div>
Do not forget that you have opportunity to set your custom validation handler.
Like this:
<div class="form-group">
<label>Username</label>
<input
type="text"
name="username"
class="form-control"
data-validation="my:valid">
<div class="form__msg"></div>
</div>
//input the 'example'
univalid.setValidHandler({
'my:valid': val => {
if(val.match(/^example$/)){
return true;
}else{
return false;
}
}
});
You are also can define message (empty, invalid, filter, success) for individual input
Add to your html form elements (inputs, selects, textarea) 'data-msg=[type]'
type:
- empty
- invalid - ValidationHandler error
- filter - Filter error (univalid-key-logger module)
- success
<div class="form-group">
<label>Username</label>
<input
type="text"
name="username"
class="form-control"
data-validation="required"
data-msg='{"empty":"This Filed empty", "invalid": "This Field Invalid", "filter": "Latin Only", "success": "Is Ok"}'>
<div class="form__msg"></div>
</div>
- Also see how to set and edit default 'msgConfig'
- Also see how to set common global 'msgConfig' for collections of forms
- Also see how to toggle form on common global 'msgConfig'
You can define filer`s handler for individual input
It Handled 'keyboard' events
Add to your html form elements (inputs, selects, textarea) 'data-f=[type]'
In current moment available patterns supporting types:
- oL - only latin symbols
- oC - only cyrillic symbols
- oN - only numbers
- oP - only numbers and latin symbols
<div class="form-group">
<label>Username</label>
<input
type="text"
name="username"
class="form-control"
data-f="oL"
data-validation="required">
<div class="form__msg"></div>
</div>
Validating the pack
pack - Type object
Structure of pack must be strict. Like that:
name, val, type - required fields
//name, val, type - required fields
[
{
name: 'username',
val: 'Uriy',
type: 'required',
filter: 'oL',
msg: {
empty: 'You shall not pass',
invalid: 'Validation error',
filter: 'Filter error',
success: 'All right'
}
},
{
name: 'email',
val: 'Uriy@mzf.com',
type: 'email',
filter: val => {
// Your custom filter
console.log('Filter', val);
// if FilterHandler is Ok then "return true"
return true;
// else "return false"
},
msg: {
empty: 'You shall not pass',
invalid: 'Bad email',
filter: 'Only lat/numbers/specials symbols',
success: 'All right'
}
},
]
core - Type object
The instance of 'univalid' module
Send form method
options - Type object
- Default sendConfig
option
options.newAjaxBody - Type object
New Ajax body config include:
- newAjaxBody.type - Type
string
- (if set 'method', that bind html attribute method) - newAjaxBody.url - Type
string
- (if set 'action', that bind html attribute action) - newAjaxBody.data - data of form
- newAjaxBody.notDisableSubmit - Type
boolean
options.cbSendSuccess - Type function
options.cbSendError - Type function
univalid.get('send', {/* options */});
core - Type object
The instance of 'univalid' module
Method of set custom statuses
pack - Type array
Each field of item of array must be strict named.
Item of pack must have three required field "name", "state", "msg".
univalid.get('setStatuses', [
{
"name": "username",
"state": "error",
"msg": "this username is used"
},
{
"name": "email",
"state": "error",
"msg": "this email is used"
}
]);
Example below shows how may to set statuses on inputs of form after get server validation result
univalid.setStrategy(UnivalidStrategyForm({
// ...
sendConfig: {
type: 'post',
url: 'registration',
cbSendError: (err, form) => {
form.setStatuses(err.response);
}
},
// ...
}));
Clear statuses of form and fields
pack - Type nodeList
Pack of html nodes inputs, selects, textareas
univalid.get('clearStatuses', [/* [ nodes ] */]);
// or clear all statuses of form
univalid.get('clearStatuses');
Clear input values
inputs - Type node or nodeList
May be one node or array of nodes
univalid.get('clearInputs', [/* [ inputs ] */]);
Add new event in form
events - Type object
May be one event or object of events
univalid.get('addEvent', {
ClickInDocument(){ document.addEventListener('click', ()=>{
console.log('Click!')
})}
});
Disable all inputs, selects, textareas
univalid.get('disable');
Enable all inputs, selects, textareas
univalid.get('enable');
Get validation handlers.
By default defined in univalid-strategy abstract class
Set the option in instance
option - Type string
univalid.set('passConfig', {min: 10, analysis: ['hasLowercase', 'hasDigits', 'hasSpecials']});
Get the prop
prop - Type string
univalid.get('passConfig');
Type object
! Required Prop
This is instance 'univalid' module
Must be define on init
Type string
! Required Prop
Form selector
Type object
Default {error: 'error', success: 'success'}
ClassName config
Type object
Default {min: 6, analysis: ['hasUppercase', 'hasLowercase', 'hasDigits', 'hasSpecials']
Password config
univalid.set('passConfig', {
min: 10,
analysis: ['hasUppercase']
});
Type object
Statuses config
univalid.set('statusConfig', {
targetParent: '.form-group',
targetStatus: '.form__msg',
successStatus: true /* if show success status */
});
Type object
SendForm config
univalid.set('sendConfig', {
type: 'method',
url: '/form',
notDisableSubmit: true,
cbSendSuccess: (res, univalidStrategyFormInstance) => {
console.log(res, univalidStrategyFormInstance)
},
cbSendError: (err, univalidStrategyFormInstance) => {
console.log(err.response, univalidStrategyFormInstance);
}
});
Type boolean
On\off keyLogger filters
univalid.set('keyLogger', true);
Type object
CheckPasswordScore config
univalid.set('checkPassScore', {
target: 'input[type="password"]',
cb: val => {
console.log(val);
}
});
Do not forget that you are also may use all methods from API univalid module.
Several examples
// getCommonState - return common state ('success' or 'error')
univalid.get('check');
if(univalid.getCommonState === 'success'){
univalid.get('send');
}
// getState - return last state of validation
univalid.get('check');
console.log(univalid.getState);
// clearState - clear last state of validation
univalid.get('check');
console.log(univalid.getState);
univalid.clearState();
// getStrategy - return current strategy
console.log(univalid.getStrategy);
// getValidHandler - return current validation handlers
console.log(univalid.getValidHandler);
You can subscribe on univalid or univalid-strategy-form events.
univalid.on('start:valid', (args) => {
console.log('Check!');
});
Table of events
Event | Description |
---|---|
start:valid | Start validation pack |
end:valid | End validation pack |
start:valid:field | Start validation field |
end:valid:field | End validation field |
change:strategy | Change strategy event |
set:new-ValidationHandler | Set new ValidationHandler event |
change:msg-config | Change message config event |
clear:state | Clear state of last validation event |
e:submit | Submit form |
e:blur | Blur event on current input |
e:focus | Focus event on current input |
e:keyup | Keyup event on current input |
error | Error event |
clear:statuses | Clear statuses event |
send:form | Send form event |
clear:inputs | Clear inputs |
ISC ©