Created
September 27, 2019 21:10
-
-
Save m3g4p0p/87e0d9ab6dfab570e72ca33b45dea01d to your computer and use it in GitHub Desktop.
Validate a string according to given HTML validation constraints
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export class Validator { | |
/** | |
* @param {string|object} constraints | |
*/ | |
constructor (constraints) { | |
/** | |
* @member {HTMLInputElement} | |
* @private | |
*/ | |
this.input = Object.assign( | |
document.createElement('input'), | |
typeof constraints === 'string' | |
? { type: constraints } | |
: constraints | |
) | |
} | |
/** | |
* @param {string} value | |
* @returns {ValidityState} | |
*/ | |
validate (value) { | |
this.input.value = value | |
return this.input.validity | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Validator
Validates a string according to given HTML validation constraints -- most notably
type="email"
, which is notoriously cumbersome to implement "manually". You most probably copy / pasted the RegExp from this classic thread on SO at some point; instead, we can just leverage the native HTML validation for a more robust solution.Usage
You can pass a string or a constraints object to the constructor; the
Validator
instance has just onevalidate()
method that takes a string and returns aValidityState
.Passing The Type
In the basic form just pass an input element type to validate against:
Passing Attributes
For more complex validation, pass an object of constraint attributes you'd apply to an input element:
Final Thoughts
Admittedly, the only real use case would be email validation, or maybe URLs.
License
MIT 2019