string-format-validation
Javascript library to format & validate strings (or Numbers)
============================
A common usage for this library is <input />
fields and validating the input and/or formatting (masking ie: phone (###) ###-####).
Built Atop Awesome Work By Others
============================
Usage
npm install string-format-validation
Format (masking)
const userInput = '9166163600'const format = '(###) ### - ####'const formattedInput = StringFormatValidation console // (916) 616 - 3600
Validate
const validationRules = name: min: 1 max: 20 email: type: 'email' zip: size: 5 const userInput1 = 'Cory'const userInput2 = 'coryrobinson42@gmail.com'const userInput3 = '90210'console // returns `true`console // returns `true`console // returns `true` because the string length is '===' 5
Validation
Available rules: (Please open an issue to request a specific rule)
min
{integer} // minimum length
max
{integer} // max length
size
{integer} // exact length
type
- date
- phone
- creditcard
- number
Rules must be in Object structure:
min: 1 // min characters allowed max: 30 // max characters allowed size: 10 type: 'phone' // any of the listed 'types' above
Format
You can use Special Characters for your format needs.
const userInput = '9166163600'const format = '(###) ### - ####'const formattedInput = StringFormatValidation console // (916) 616 - 3600
Character | Description |
---|---|
0 |
Any numbers |
9 |
Any numbers (Optional) |
# |
Any numbers (recursive) |
A |
Any alphanumeric character |
a |
Any alphanumeric character (Optional) Not implemented yet |
S |
Any letter |
U |
Any letter (All lower case character will be mapped to uppercase) |
L |
Any letter (All upper case character will be mapped to lowercase) |
$ |
Escape character, used to escape any of the special formatting characters. |
Putting It Together - Validate & Format
const rules = name: min: 1 max: 20 email: type: 'email' phone: format: '(###) ### - ####' size: 13 // must include formatting added characters ie: '()' & '-' const userInputs = name: 'cory' email: 'coryrobinson42' // not a valid email phone: '9166163600' console/* returns: { name: true, email: false, phone: { valid: true, format: '(916) 616 - 3600' } }*/
Note:
When invoking StringFormatValidation(rulesMap, userInputMap)
rulesMap
can be an
object of keys that contain the rules for the respective key matching up to the key in userInputMap
, ie:
const rulesMap = // this key declares the rules (format/validation) for 'firstname' key in `userInputMap` firstName: max: 20 const userInputMap = // this key string is matched against the rules in `rulesMap` under the same key firstName: 'cory' // returns: { firstName: true } <-- validation
You can also simply pass an Object of validation/format rules as the first argument and a string as the second argument, ie:
// returns: { valid: false, format: '(916) 61'}
===========================