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

How can we add custom remote validator without the ClientSideValidations::Middleware::Base like in the wiki #748

Closed
dinatih opened this issue Jul 18, 2018 · 5 comments

Comments

@dinatih
Copy link

dinatih commented Jul 18, 2018

wiki : https://github.com/DavyJonesLocker/client_side_validations/wiki/Custom-Validators#remote-validators

System configuration

Client Side Validations version:
after this commit 35501c1

Is there another way to add custom remote validators, please ?

@factor4
Copy link

factor4 commented Jul 19, 2018

I solved that as follows:

# config/routes.rb
resources :users do
  collection do
    get :check_my_value
  end
end

# controllers/users_controller.rb
def check_my_value
  user = User.new(my_value: params[:id])
  user.validate
  if user.errors[:my_value].blank?
    head :ok
  else
    render json: { error: "My error message." }, status: :not_found
  end
end
// app/assets/javascripts/users.js
ClientSideValidations.validators.remote['my_value'] = function(element, options) {
  if ($.ajax({
    url: '/users/check_my_value',
    data: { id: element.val() },
    // async *must* still be false. Could not find another solution in a hurry...
    async: false
  }).status == 404) { return "My error message."; }
  // TODO Fetch the error message from the Ajax response.
}

It's up to you to protect the method from unauthorized access. In my case only logged in users can access it, but this will not fit any use-case e.g. register a new user.

@dinatih
Copy link
Author

dinatih commented Jul 19, 2018

Thanks you @factor4 I will try that.

@tagliala
Copy link
Contributor

@factor4 thanks.

Still hadn't time to fix the wiki

Please also be aware of information disclosure and DOS attacks: the above endpoints should be protected with something like rack-attack

@tagliala
Copy link
Contributor

Hmm... just remembered about this comment: #710 (comment)

I just need to copy & paste to the wiki and add disclaimers

@dinatih dinatih closed this as completed Jul 19, 2018
@tagliala
Copy link
Contributor

Wiki updated: https://github.com/DavyJonesLocker/client_side_validations/wiki/Custom-Validators#remote-validators

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

No branches or pull requests

3 participants