Skip to content

Instantly share code, notes, and snippets.

@m3g4p0p
Created September 27, 2019 21:10
Show Gist options
  • Save m3g4p0p/87e0d9ab6dfab570e72ca33b45dea01d to your computer and use it in GitHub Desktop.
Save m3g4p0p/87e0d9ab6dfab570e72ca33b45dea01d to your computer and use it in GitHub Desktop.
Validate a string according to given HTML validation constraints
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
}
}
@m3g4p0p
Copy link
Author

m3g4p0p commented Sep 27, 2019

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 one validate() method that takes a string and returns a ValidityState.

Passing The Type

In the basic form just pass an input element type to validate against:

const emailValidator = new Validator('email')

emailValidator.validate('foo') // { valid: false, typeMismatch: true }
emailValidator.validate('foo@bar.baz') // { valid: true }

Passing Attributes

For more complex validation, pass an object of constraint attributes you'd apply to an input element:

const patternValidator = new Validator({ pattern: '^foo$', required: true })

patternValidator.validate('foo') // { valid: true  }
patternValidator.validate('baz') // { valid: false, patternMismatch: true }
patternValidator.validate('') // { valid: false, valueMissing: true }

Final Thoughts

Admittedly, the only real use case would be email validation, or maybe URLs.

License

MIT 2019

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment