This tool provides some basic validation behavior intended to work alongside the Ruby on Rails unobtrusive scripting adapter.
Install the module:
yarn add rails-validator
Import it in your javascript (es6):
import 'rails-validator/dist/rails-validator'
import Rails from 'rails-ujs'
Rails.start()
Or require the files in the asset pipeline:
//= require rails-validator/dist/rails-validator
//= require rails-ujs
Create forms with data-remote=true
to enable the ujs.
Options
data-errors
: Set toinline
for inline error messages andalert
to use a browser alert dialog.data-success
: Set to any string to trigger a redirect on a successful response, orreload
to reload the current page.
Example
<form action="/contact" data-remote="true" data-errors="inline" data-success="/thank-you">
</form>
The validator assumes you are using standard http status codes and JSON formats in your Rails controllers.
If you are using the responders gem, you are likely already sending the correct responses.
With Responders
class UsersController
def create
user = User.create(user_params)
respond_with user
end
end
Without Responders
class UsersController
def create
user = User.new(user_params)
if user.save
render json: user, status: :created
else
render json: { errors: user.errors }, status: :unprocessable_entity
end
end
end