Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Async rule #98

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open

Async rule #98

wants to merge 4 commits into from

Conversation

ej2015
Copy link
Contributor

@ej2015 ej2015 commented Jun 9, 2019

My attempt at bringing in async validation rules(#40). Main ideas:

  • Refactor message method into two new methods: validate does the validation, message does the rendering
  • Validations are handled as promises

Usage Example:

const getNews = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => resolve('good news!'), 1000)
  })
}

const validator = new SimpleReactValidator({
  validators: {
    is_good: {
      message: 'The :attribute must be good.',
      rule: (val, params, validator) => {
        return getNews().then(res => {
          return res === 'good news !'
        })
      }
    }
  }
})

class Form extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      health: ''
    }
  }

  submitForm = event => {
    event.preventDefault()
    validator.validate('health', this.state.health, 'required|is_good')
    .then(() => {
    if (validator.allValid()) {
      console.log(this.state)
    } else {
      validator.showMessages()
      this.forceUpdate()
    }
    })
  }

  setName = e => {
    this.setState({ name: e.target.value })
  }

  render() {
    return (
      <form onSubmit={this.submitForm}>
        <div>
          <label> Health </label>
          <input
            value={this.state.health}
            onChange={this.setHealth}
          />
          {validator.message('health')}
        </div>

        <button type='submit'>Submit</button>
      </form>
    )
  }
}

export default Form

@stuyam stuyam self-assigned this Jun 10, 2019
@stuyam
Copy link
Collaborator

stuyam commented Jun 10, 2019

@ej2015 coming in hot with another PR! Awesome! My big issue with this approach is is changes fundamentally how SRV works, which I am not against but if we can do it without changing the API I think that would be even better.

I started a branch a while back, then abandoned it because life happens, here is what I got to: master...async-validators

It doesn't really work so take it with a grain of salt. But the main idea is that you can define validators as async which then put them into a separate bucket of validators. The regular validators will always run like normal, and only once someone tries to submit will it call each of the async validators. This separation is important to keep the fast responses of the regular validators and keep the long async validators to only happen manually and less often.

I thought the sync validators would sort of work like a middleware where once one completes it calls the next one, if one fails it will stop the chain and throw an error, else it will get through them all and complete.

The only api changes would be that is adds the ability to add an async rule and it adds a new pass and fail callback setup which looks something like this:

  submitForm() {
    this.setState({processing: true});
    this.validator.asyncValid({
      pass: () => {
        alert('You submitted the form and stuff!');
        this.setState({processing: false});
      },
      fail: () => {
        this.validator.showMessages();
        this.setState({processing: false});
      }
    });
  }

This still leaves the normal way of calling this.validator.allValid() but adds this for async. It calls the pass or fail closure depending on what happens during the request.

Again this does not work but it is a little bit more along the lines of where I was hoping to move with this. Open to discussion.

@ej2015
Copy link
Contributor Author

ej2015 commented Jun 13, 2019

Was looking at your branch. Can you explain more what the async validator is supposed to look like? And why did you say it's not working?

@stuyam stuyam mentioned this pull request Jun 14, 2019
@stuyam
Copy link
Collaborator

stuyam commented Jun 14, 2019

@ej2015 all I was saying was my old branch wasn't working 100%. Just opened a pull request for a new brach that I pulled most of the changes over and got it working. Would be interesting to hear you feedback: #103

@stuyam stuyam removed their assignment Sep 22, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants