Skip to content
This repository has been archived by the owner on Dec 9, 2022. It is now read-only.

v2 - rewrite #23

Closed
on3iro opened this issue Feb 8, 2018 · 1 comment
Closed

v2 - rewrite #23

on3iro opened this issue Feb 8, 2018 · 1 comment
Labels
enhancement New feature or request Priority: High

Comments

@on3iro
Copy link
Owner

on3iro commented Feb 8, 2018

Living on the fastlane.

Vally isn't even a week old and I am already thinking about a rewrite 😅

I want vally to become more functional and flexible. So DOM-manipulation should be deferred to the user as much as possible (apart from makeValidationWithBindings). Here are a few thoughts on how to achieve this:

  • Instead of handing selector strings for fields, we could directly use the HTMLInputElements
  • The validation itself could be promise based and return an array of failed fields (more on that below)
  • Validators become an object instead of a single function
type ValidatorFn = (any) => boolean
type Validator = {|
    type: string,
    fn: ValidatorFn,
    msg: string
|}

When iterating over a fields validators we can then resolve the promise with the following content

const validateValue = (
  node: HTMLInputElement,
  validators: Array<Validator>
):Promise => validators.reduce((acc, validator, i) => {
  const val = node.value

  const isValid = validator.fn(node)
  const newAcc = {
      node,
      validator,
      isValid: (acc.isValid && isValid)
  }
  const isLast = i === validators.length - 1
  if (isLast) return Promise.resolve(newAcc)

  return newAcc
}, { isValid: true })

That way the user is in charge of how to handle and react to each individual field change (#22 would be no longer necessary) :

Example

const myNameInput = document.getElementById('js-name-input')
vally.validate([
 {
    field: myNameInput,
    validators: [
        { type: 'isNotEmpty', msg: 'Please enter a name.', fn: isNotEmpty },
    ]
 }   
]).then((results) => {
    results.forEach(res => { /* user does something in response */ })   
})

Another advantage of this approach would be, that because we already get the nodes to validate
we can now merge validators, that run on the same node ( #19 ).

One problem with the promise-based approach would be, that whis would not work in IE by default.

@on3iro on3iro added the enhancement New feature or request label Feb 8, 2018
@on3iro
Copy link
Owner Author

on3iro commented Feb 8, 2018

The more I think about it we probably do not even need promises here.
Simply returning the results array would do the trick. The user can then do whatever he/she wants with it.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
enhancement New feature or request Priority: High
Projects
None yet
Development

No branches or pull requests

1 participant