Closed dinatih closed 6 years ago
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.
Thanks you @factor4 I will try that.
@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
Hmm... just remembered about this comment: https://github.com/DavyJonesLocker/client_side_validations/issues/710#issuecomment-312624313
I just need to copy & paste to the wiki and add disclaimers
wiki : https://github.com/DavyJonesLocker/client_side_validations/wiki/Custom-Validators#remote-validators
System configuration
Client Side Validations version: after this commit 35501c1b120a3d0d5b8a907e4edd6d7b826378e6
Is there another way to add custom remote validators, please ?