validates_inclusion_of
in js-style. And that heme is no longer supported.Email
email
- email addressfrequency
- the frequency with which the newsletter will go to this addressemail
requiredemail
must be uniqueemail
should be email (with a dog and other ryushechkami)frequency
is optional, but if so, it should be in the range from 1 to 7 class Email < ActiveRecord::Base before_save { self.email = email.downcase } VALID_EMAIL_REGEX = /\A[\w+\-.]+@[az\d\-.]+\.[az]+\z/i validates :email, presence: true, uniqueness: { case_sensitive: false }, format: { with: VALID_EMAIL_REGEX } validates_inclusion_of :frequency, in: 1..7, allow_blank: true end
class EmailsController < ApplicationController def new @email = Email.new end def create @email = Email.new(email_params) if @email.save flash[:success] = 'Email !' redirect_to emails_url else render :new end end private def email_params params.require(:email).permit(:email, :frequency) end end
%h1 = form_for @email do |f| = render partial: 'shared/error_messages', locals: { object: f.object } %p= f.text_field :email, placeholder: '' %p= f.text_field :frequency, placeholder: ' ' %p= f.submit '!'
$('#form').validate();
I will repeat the link to the documentation for the plugin in order not to return to it anymore. There is a small problem with the structured content, but all the information is there.
jQuery -> validate_url = '/emails/validate' $('#new_email, [id^=edit_email_]').validate( debug: true rules: 'email[email]': required: true remote: url: validate_url type: 'post' 'email[frequency]': remote: url: validate_url type: 'post' )
validate_url = '/emails/validate'
$('#new_email, [id^=edit_email_]').validate
debug: true
rules:
'email[email]':
remote: url: validate_url type: 'post'
remote
. With it, we can send ajax requests to the server and process the returned data.json
:true
- it means that everything is ok with the fieldfalse
, undefined
or null
responses, as well as any other string'
are regarded by the method as a signal of failed validation required: true
validates_presence_of
(that is, presence validation). This is due to the peculiarities of the validator - it pulls the remote
method only if any data is entered in the field. "Run by hand" this check is impossible, therefore, validation of availability is prescribed directly through this method. By the way, it takes a function as an argument, so complex logical checks for presence can (and should) be performed through it. def validate # end
resources :emails post 'emails/validate', to: 'emails#validate', as: :emails_validation
'/emails/validate'
Email
creation form in the browser (lvh.me Tre000/emails/new), type “something” in the form field and run to the console - see what the validator reports to us. Started POST "/emails/validate" for 127.0.0.1 at 2014-02-17 22:10:31 +0000 Processing by EmailsController#validate as JSON Parameters: {"email"=>{"frequency"=>"-"}}
json
flown to the controller, we will create a new Email
object in memoryActiveModel
ActiveModel::Errors
(available through the errors
method) is ActiveModel::Errors
in memory, in which there will be a hash @messages
- either with errors (if the attributes are not validated), or empty (if everything is fine with the object)true
, and if there are errors in the attribute being checked, we will reply with the text of these errors, which will be considered by the plugin’s receiving method as failed validation. And, moreover, the plugin uses the received string as the text of the error message. ru: activerecord: attributes: email: email: "" frequency: "" errors: models: email: attributes: email: blank: "" taken: " " invalid: " " frequency: inclusion: " 1 7 "
Read about I18n in Rails guides: http://guides.rubyonrails.org/i18n.html
def validate email = Email.new(email_params) email.valid? field = params[:email].first[0] @errors = email.errors[field] if @errors.empty? @errors = true else name = t("activerecord.attributes.email.#{field}") @errors.map! { |e| "#{name} #{e}<br />" } end respond_to do |format| format.json { render json: @errors } end end
email = Email.new(email_params) email.valid?
ActiveModel::Errors
object ActiveModel::Errors
in the memory. The @messages
hash with errors, in addition to the ones we need for the attribute being checked, will contain messages for all other attributes (since the values ​​of all the others are nil
, only the value of the attribute being checked arrives). (rdb:938) email.errors #=> #<ActiveModel::Errors:0x007fbbe378dfb0 @base=#<Email id: nil, email: nil, frequency: "-", created_at: nil, updated_at: nil>, @messages={:email=>["", " "], :frequency=>[" 1 7 "]}>
(rdb:938) email.errors['frequency'] #=> [" 1 7 "]
params
hash: # (rdb:938) params #=> {"email"=>{"frequency"=>"-"}, "controller"=>"emails", "action"=>"validate"} # , (rdb:938) params[:email] #=> {"frequency"=>"-"} # , (rdb:938) params[:email].first #=> ["frequency", "-"] # , -> (rdb:938) params[:email].first[0] #=> "frequency"
field = params[:email].first[0] @errors = email.errors[field]
if @errors.empty? @errors = true else name = t("activerecord.attributes.email.#{field}") @errors.map! { |e| "#{name} #{e}<br />" } end
@errors
variable is true
(this is the answer the plugin expects if there are no errors).@errors
, then we get the message “must be in the range from 1 to 7 inclusively” (and if there are several, they just “stick together” when outputting)name = t("activerecord.attributes.email.#{field}")
@errors.map! { |e| "#{name} #{e}
" }
br
at the end of each error, it depends on the layout, in short, add to tastejson
: respond_to do |format| format.json { render json: @errors } end
# post 'emails/validate', to: 'emails#validate', as: :emails_validation # post ':controller/validate', action: 'validate', as: :validate_form
def validator(object) object.valid? model = object.class.name.underscore.to_sym field = params[model].first[0] @errors = object.errors[field] if @errors.empty? @errors = true else name = t("activerecord.attributes.#{model}.#{field}") @errors.map! { |e| "#{name} #{e}<br />" } end end
def validate email = Email.new(email_params) validator(email) respond_to do |format| format.json { render json: @errors } end end
onkeyup: false
entered by the user in the form fields, set the value of the onkeyup: false
method onkeyup: false
Source: https://habr.com/ru/post/213077/
All Articles