1
client_side_validations 페이지에서 코드를 복사했습니다. 그리고 나는 오류가있었습니다 undefined method validates_email for #<Class:0x007ff3382428a8>
includes ::Validations
을 제 모델에 넣었을 때이 오류는 사라졌지만 유효성 검사가 전혀 작동하지 않습니다.클라이언트 측 검증 미확인 메소드`validates_email '
응용 프로그램/검증/email_validator.rb
class EmailValidator < ActiveModel::EachValidator
def validate_each(record, attr_name, value)
unless value =~ /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i
record.errors.add(attr_name, :email, options.merge(:value => value))
end
end
end
# This allows us to assign the validator in the model
module ActiveModel::Validations::HelperMethods
def validates_email(*attr_names)
validates_with EmailValidator, _merge_attributes(attr_names)
end
end
설정/로케일/en.yml
# config/locales/en.yml
en:
errors:
messages:
email: "Not an email address"
응용 프로그램/자산/자바 스크립트/rails.validations.customValidators.js
// The validator variable is a JSON Object
// The selector variable is a jQuery Object
window.ClientSideValidations.validators.local['email'] = function(element, options) {
// Your validator code goes in here
if (!/^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i.test(element.val())) {
// When the value fails to pass validation you need to return the error message.
// It can be derived from validator.message
return options.message;
}
}
모델/설명 .rb
class Comment < ActiveRecord::Base
attr_accessible :content, :email, :ip, :name, :post_id
belongs_to :post
validates_presence_of :content, :email, :post_id, :name
validates_email :email
end