judgegem / judge Goto Github PK
View Code? Open in Web Editor NEWClient-side form validation for Rails
License: MIT License
Client-side form validation for Rails
License: MIT License
I am attaching an image because is more easy to look than write:
This is a sign_in form (field request are email and password), as you can see in the image the gem load in data-validable all another bunch of validation that are not present in my form.
The most evident is the confirmation password, I have that validation in my user model, but i have for a sign_up form, in another page. Why the validator load also this? actually it loads all the possible validation present in the model for a specific field.
How this is possible?
I really don't understand it.
Any thoughts, words or ideas would be more than appreciated.
Best
Dinuz
Judge doesn't support options like :if and :unless on validations, which makes perfect sense. However, I don't think the way validations with these options are currently treated is correct.
Currently, the initializer in Judge::Validator simply strips the unsupported options away. For a conditional validation (e.g. with :if), this means that the condition is removed and the validation becomes unconditional on the client side, which can lead to all kinds of problems (e.g. forms that can't be submitted due to a validation failing when that validation shouldn't be active).
I think the correct behaviour would be to ignore validations with unsupported options (i.e. reject the entire validation instead of just the option), so they aren't 'transferred' to the client.
In my view, it's better to have no validations on the client side for these cases than to have validations that behave differently than how they are defined on the model.
Any thoughts?
/^[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,4}$/i is a rub regex for simple mail format validation.
Judge will fail the test for an emal like "[email protected]" without the quotes. I believe the problem is in the /i part of the regex not been correctly transformed by judge into a case insensitive/insensitive modifyer for javascript.
Hello @joecorcoran I am getting above JS error when using this Gem with Rails 4.1.5 + ruby 2.1 (simple_form). Any fix for this?
Thanks,
Gaurav
I am trying to use the gem judge and uniqueness validation, but sometimes I am getting a weird error, at most of time, after a validation fail.
After that, the XHR request always return this:
["Judge validation for Person#name not allowed"]
Started GET "/judge?klass=person&attribute=name&value=joao&kind=uniqueness" for 127.0.0.1 at 2014-04-17 01:13:59 -0300
Processing by Judge::ValidationsController#build as JSON
Parameters: {"klass"=>"person", "attribute"=>"name", "value"=>"joao", "kind"=>"uniqueness"}
Completed 200 OK in 7ms (Views: 0.1ms | ActiveRecord: 0.0ms)
But, if I reload the server and the page, all it will worked fine one or there times, before i change the page or get one uniqueness error (i think)
Thanks,
The code
class Person < ActiveRecord::Base
#person.rb
validates :name, presence: true, uniqueness: {case_sensitive: false}, length: {minimum: 2, maximum: 200}
validates :email, uniqueness: true, length: {maximum: 30}, format: {with:/\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i}, allow_blank: true
validates :cpf, presence: true, uniqueness: true, length: {minimum: 10, maximum: 14}, cpf: true
end
#config/initializers/judge.rb
Judge.configure do
expose Person, :name, :email, :cpf
end
#people.js.coffee
jQuery ->
$('#person_name').blur ->
judge.validate document.getElementById("person_name"),
valid: (element) ->
element.style.border = "1px solid green"
$(element).nextAll().remove()
return
invalid: (element, messages) ->
element.style.border = "1px solid red"
$(element).nextAll().remove()
$(element).after '<p class=\"text-danger\">' + messages.join(',') + '</p>'
return
return
I just saw that if I enter a blank space in the club#name
input the validation passes.
So, I changed my model club.rb
from this:
validates :name, :presence => true
to
validates :name, :presence => true, :allow_nil => false, :allow_blank => false
But the space is still considered as valid.
I'm wondering if the allow_blank option is respected by judge
or if I made a mistake somewhere. Could you confirm that this option works correctly? Thanks.
Hi,
I'm just wondering if Judge is supposed to use this ^ automatically or if the expected behavior is for Judge to validate all of the fields before they are ever entered by the user. For me, Judge is showing a form of red before the user enters anything.
Thanks,
Erik
I am trying to use the gem judge and presence email validation. But everytime, if I input any e-mail, display, that is not valid.
If remove :validatable from Devise, validate is working. How solve this issue? Thanks)))
I am working in rails 5, maybe problem support rails 5?
Its my code:
user.rb
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
has_one :freelancer, dependent: :destroy
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :confirmable, :lockable
validates :username, presence: true, uniqueness: true
validates :email, presence: true
before_validation :ensure_username_has_a_value
private
def ensure_username_has_a_value
if self.username.nil?
self.username = self.email unless email.blank?
end
end
end
new.html.erb:
<div class="login_page">
<%= form_for(resource, as: resource_name, url: registration_path(resource_name), :builder => Judge::FormBuilder, html: { class: "new_user"} ) do |f| %>
<div class="item">
<%= f.label :email, 'E-mail' %>
<div class="field">
<%= f.email_field :email, :validate => true, autofocus: true, placeholder: "E-mail" %>
</div>
</div>
<div class="item">
<%= f.label :username, 'Nickname' %>
<div class="field">
<%= f.text_field :username, placeholder: "Nickname" %>
</div>
</div>
<div class="item">
<label>Password</label>
<div class="field">
<% if @minimum_password_length %>
<em>(<%= @minimum_password_length %> characters minimum)</em>
<% end %><br />
<%= f.password_field :password, autocomplete: "off", placeholder: "password" %>
</div>
</div>
<div class="item">
<label>Password again</label>
<div class="field">
<%= f.password_field :password_confirmation, autocomplete: "off", placeholder: "Password again" %>
</div>
</div>
<div class="buttons">
<%= f.submit "Sign up", class: "button button_green" %>
<div class="links">
<%= link_to "Forgot your password?", new_password_path(resource_name) %>
<%= link_to "Didn't receive confirmation instructions?", new_confirmation_path(resource_name) %>
</div>
</div>
<% end %>
</div>
judge.rb
Judge.configure do expose User, :email end
registration.js
jQuery(document).ready(function() { $('#user_email').blur(function(){ judge.validate($("#user_email")[0], { valid: function(element) { element.style.border = '1px solid green'; }, invalid: function(element, messages) { element.style.border = '1px solid red'; alert('Элемент foo потерял фокус.'); alert(messages.join(',')); } }); }); });
Consider this relationship between Person and Email:
class Person < ActiveRecord::Base
# ...
has_one :email
accepts_nested_attributes_for :email
end
class Email < ActiveRecord::Base
attr_accessible :address
belongs_to :person
validates :address, :uniqueness => true
end
In a form for a person object, we may wish to pass the person's email back and save it along with the person:
<%= form_for @person, validate: true do |f| %>
<%= f.text_field :username, validate: true %>
<%= f.fields_for :email, @person.email do |email_f| %>
<%= email_f.text_field :address, validate: true %>
<% end %>
<div class='actions'>
<%= f.submit "Update" %>
</div>
<% end %>
The problem is that the email address field in this form will have the attribute:
name="user[email_attributes][address]"
Meaning that when Judge attempts to validate uniqueness for this field, it will attempt to check the EmailAttributes model (which does not exist), rather than the Email model.
Is there a way to perform the validation by default instead of always validate: true
for each field? Basically I want to use it always, and set it to false
when I don't need it.
If judge doesn't allow us to do such thing I'll fork the gem, which file should I change? (Basically change a if
statement by allowing nil
value to perform validation too, not be forced to expect a true
)
Thanks!
This should be easily achievable now, by using a mounted Rails::Engine. I'd like to keep support for Rails 3.0.x apps, so might need to make this an optional feature.
When applying confirmation validation:
validates :password, confirmation: true
The data-validate
get's attached to the original field. This makes for a bad user experience if you're triggering validations on blur. When you fill out the original field and tab to the confirmation an error will be triggered before you get a chance to fill out the confirmation.
There are ways to hack a fix with JS, but I think a better solution would be to attach the data-validate
to the confirmation field by default.
I plan on looking into this an submitting a PR, but I thought I'd add an issue in case someone wanted to tackle it first or tell me why it's a bad idea.
thanks
Hi.
I correctly configured my initializer/judge.rb
Judge.configure do
expose Club, :name
expose Team, :login
end
But, sometimes, after I reload the page after changed something in the source code I get this message Judge validation for Club#name not allowed
. I need to restard the server to fix it.
A little boring, but I would like to know why and I hope there will be no such issue in production, because I basically don't know why this bug happens.
Do you?
Thanks.
I worked around this with
# fix the presence validator for radio buttons
judge.eachValidators.presence = (options, messages) ->
if $(@).is(':radio')
judge.closed(if $("[name=\"#{@.name}\"]:radio:checked").length then [] else [messages.blank])
else
judge.closed(if @value.length then [] else [messages.blank])
for now. It should probably be solved with a more generic value = (elem) -> submitted_field_value
function and then checking value(this)
instead of this.value.length
.
There are big differences between the regular expression capabilities of Ruby and JavaScript. It's not within the scope of this project to bridge the gap, but it does cause problems for certain typical uses of the format validator. See issue #5 for an example.
At the moment, I'm thinking that the best way to solve this is to write a plugin for XRegExp which will add some of the more commonly used Oniguruma features (character types and anchors, POSIX bracket syntax for character classes). We can then use XRegExp in place of the native RegExp in Judge's client-side format validator method.
Hi. I've been working on a Coffeescript class to handle Judge validations. It is based off a Javscript I found here. It's throwing errors related to Underscore.js.
When I instantiate my class judgment = new JudgeJudy({form: $("#new_suggestion")})
I'm seeing this error in the console:
Uncaught TypeError: func.apply is not a function
and it references line 683 in the Underscore.js library.
Here's that Coffeescript:
# This class was inspired by code found
# here: http://blog.bananacoding.com/blog/client-side-form-validation-using-judge-gem
@JudgeJudy = class JudgeJudy
constructor: (@options)->
@form = @options.form
@validate_form()
valid: (element, deferred)->
$(element).removeClass('error').addClass('valid')
deferred.resolve()
invalid: (element, deferred)->
$(element).removeClass('valid').addClass('error')
deferred.reject()
validate_form: ->
that = @
@form.on 'submit', (event) ->
event.preventDefault()
$('.error_container').empty()
defers = []
that.form.find('.form-control').each (index, element)->
defers.push(that.validate_input_async(element))
$.when.apply($, defers).done ->
that.form.unbind 'submit'
that.form.submit()
validate_input_async: (element)->
deferred = new $.Deferred()
q = judge.validate element,
valid:
@valid element, deferred
invalid:
@invalid element, deferred
deferred.resolve() if q.validations.length
deferred
I was poking around the Judge repository and noticed that the Underscore version in use is 1.4.4 but Underscore.js is currently at 1.8.3. I'm not sure if it's my code, Underscore, or something else but I'm wondering how you would recommend I update this Underscore library to the latest version to see if that resolve my issue.
I struggled for a whole day thinking it was my call to apply
on $.when
that was throwing the error but then I got smart and actually looked at the error message closely. 😸
If you've got any feedback or ideas I'm all ears!!
i want to use ransack with judge.
but judge form builder's superclass is Application::Helpers::FormBuilder.
ransack form builder's superclass is Ransack::Helpers::FormBuilder.
superclass changing is very difficult.
Do you have any ideas?
For example, this topic don't work.
https://github.com/charliesome/charlie.bz/blob/master/posts/changing-the-superclass-of-a-class-in-ruby.md
Rails legth validation counts new lines as two character and Judge's JS counts them as one. This can create a scenario where Judge is incorrectly validating objects.
Example
validates :description, length: { maximum: 20 }
Description value:
I am a description
Valid in Judge, valid in Rails
I am
a
description
Valid in Judge, invalid in Rails
Hi Guys,
I'm using SimpleForm. Judge return valid, but radio is not selected.
I suspect he returns valid because the tag 'value' has value, which is 'male' and 'female', have any solutions?
<%= f.input :gender, required: true, collection: [[:male, t('male')],
[:female, t('female')]], label_method: :last, value_method: :first,
as: :radio_buttons, item_wrapper_class: 'radio-inline', validate: true %>
<div class="form-group radio_buttons required user_gender">
<label class="radio_buttons required control-label">
<abbr title="obrigatório">*</abbr> sexo
</label>
<span class="radio radio-inline radio__label">
<input class="radio_buttons required form-control"
data-validate="[{"kind":"presence","options":{},"messages":{"blank":"não pode ficar em branco"}}]"
data-klass="User" type="radio" value="male" name="user[gender]" id="user_gender_male">
<label class="collection_radio_buttons" for="user_gender_male">papai</label>
</span>
<span class="radio radio-inline radio__label">
<input class="radio_buttons required form-control"
data-validate="[{"kind":"presence","options":{},"messages":{"blank":"não pode ficar em branco"}}]"
data-klass="User" type="radio" value="female" name="user[gender]" id="user_gender_female">
<label class="collection_radio_buttons" for="user_gender_female">mamãe</label>
</span>
</div>
Thanks :)
Your gem is fantastic and working well on my Rails 4 app. However, I noticed that it's printing error messages twice on String types. I have a text field where I am using this Gem for website validation for instance, and it is returning 'is invalid is invalid' on running 'Judge.validate' only one time. Is there a solution for this? Thanks, and thank you for a fantastic product!
Hi, I like the gem, but what do you think about possibility to add the formtastic support?
Uniquness validator is fired, but when didnt have value in input(deleted or not added at all), presence validation didnt fire.(border didnt become green/red). When comment uniqueness validation in Post model, presence validation for both attributes work like expected.
I`m using ruby 2.1.5, rails 4.1.8, judge 2.0.5
$(document).ready ->
$('#new_post').on 'submit', (e)->
judge.validate document.getElementById('post_title'),
valid: (element)->
element.style.border = '1px solid green'
invalid: (element, messages)->
element.style.border = '1px solid red'
judge.validate document.getElementById('post_content'),
valid: (element)->
element.style.border = '1px solid green'
invalid: (element, messages)->
element.style.border = '1px solid red'
e.preventDefault()
class Post < ActiveRecord::Base
validates :title, :content, presence: true
validates :title, uniqueness: true
end
When I attempt to update an existing record, the uniqueness validation for a field indicates the field
value already is taken. It is not taking into account that the record I am editing is the
one that has the existing value.
Opening this discussion.
json2.js
is only needed for IE < 8 according to http://caniuse.com/#feat=json – can we stop shipping this and leave it to users to work out whether they need legacy IE support? I would vote to remove it and leave a helpful note about legacy support in the documentation.judge.js
Thoughts?
So let's extract it and make it optional. :)
Hi.
I'm currently migrating my application from simple_form 2.1
to judge 2.0.3
with the judge-simple_form
plugin to keep the compatibility and keep to use the same code. I previously used clientSideValidation
to perform validations before send the forms, but it's not maintained anymore.
I followed the steps in the README but so far it doesn't works in my application.
Basically, no validation seems to be executed, the form is sent like if they were no validation and even if the club name is empty the form goes to the next step.
Here are the steps I did:
gem 'judge' # Replace client_side_validations for the new v3 version.
gem 'judge-simple_form' # Plugin to continue to use the simple_form code.
gem 'simple_form'
config.wrappers :jquery_mobile, :tag => false do |b|
b.use :html5
b.use :placeholder
b.use :label
b.use :error, :wrap_with => { :tag => 'span', :class => 'help-inline' }
b.use :hint, :wrap_with => { :tag => 'span', :class => 'help-block' }
b.use :input
b.use :judge
end
Judge::Engine
in my routes.rb and create a script that use the same path client side.//= require underscore
//= require json2
//= require judge
//= require_tree ./application
validates :name, :presence => true
.container.club
.row
.col-md-12.col-sm-12
%p= t('new_club_explanation')
= simple_form_for @club, validate: true, url: wizard_path, method: :put, html: { role: 'form' } do |f|
= f.input :name, input_html: { autofocus: 'autofocus' }, :validate => true
= f.input :description
.actions
= f.submit class: 'btn-form', value: t('next')
= link_to t('cancel'), '#', class: 'close_popup cancel_button'
:javascript
judge.validate(document.getElementById('club_name'), {
valid: function(element) {
element.style.border = '1px solid green';
},
invalid: function(element, messages) {
element.style.border = '1px solid red';
alert(messages.join(','));
}
});
What am I missing here?
Thanks.
I am choosing client_side_validations and judge.
thanks
I'm using devise, and it looks like there is a way to customize those error messages, but this question is directed at customizing the Judge portion. e.g. I'm getting Judge validation for User#
... in some of my error messages. Can I remove/change that somehow? Thank you.
I can't seem to get judge to validate my email field. If I turn off validation the field the form validates and can be submit. I have stopped using devise's :validatable
module because of some of the custom logic I'm doing around validation. Judge seems to be responding to the uniques query fine. The user doesn't exist.
Started GET "/judge?klass=user&attribute=email&value=bob%40example.com&kind=uniqueness" for 127.0.0.1 at 2014-10-09 20:54:49 -0700
Processing by Judge::ValidationsController#build as JSON
Parameters: {"klass"=>"user", "attribute"=>"email", "value"=>"[email protected]", "kind"=>"uniqueness"}
User Exists (12.1ms) SELECT 1 AS one FROM "users" WHERE "users"."email" = '[email protected]' LIMIT 1
Completed 200 OK in 17ms (Views: 0.1ms | ActiveRecord: 12.1ms)
Model:
class User < ActiveRecord::Base
validates :email, presence: true
validates :email, uniqueness: true
validates :email, format: { with: /.+@.+/, message: "must contain \"@\""}
with_options if: :should_validate? do |admin|
admin.validates :password, presence: true
admin.validates :password, confirmation: true
admin.validates :password, length: { in: 8..128 }
admin.validates :first_name, presence: true
admin.validates :last_name, presence: true
end
def should_validate?
admin? || persisted?
end
end
controls = {}
$(".participate-form__form-section").each (i, e) ->
# console.log "building collection of controls"
# get the section's inputs
id = "fs-#{i + 1}"
# console.log id
inputs = document.querySelectorAll(".participate-form__form-section##{id} input[type=text], .participate-form__form-section##{id} input[type=email]")
controls["#{id}"] = inputs
# On click, show the form section referenced in the href
$(".next-btn").on "click", (e) ->
e.preventDefault()
isValid = false
# Add logic to manage the validations per sheet
id = $(this).parent().attr("id")
isValid = validate_section(controls[id])
console.log "section is valid: #{isValid}"
if isValid
#do some stuff to prompt the user
validate_section = (controls) ->
console.log controls
results = []
for control in controls
results.push(validate_field(control))
console.log results
!(results.indexOf(false) >= 0)
validate_field = (control)->
# console.log id
isValid = false
judge.validate(control,
valid: (element) ->
# console.log "valid"
isValid = true
invalid: (element, messages) ->
id = element.getAttribute("id")
# console.log "invalid"
console.log messages
$("##{id}").popover({
# trigger: "manual"
# html : true,
placement: "left",
content: messages
}).popover('show')
$("##{id}").toggleClass("invalid-field", true)
)
console.log "#{control.getAttribute("id")} is #{isValid}"
isValid
The generated HTML is:
<input class="participate-form__input-field" data-validate="[{"kind":"presence","options":{},"messages":{"blank":"can't be blank"}},
{"kind":"uniqueness","options":{},"messages":{}},
{"kind":"format","options":{"with":"(?-mix:.+@.+)","message":"must contain \"@\""},"messages":{"invalid":"must contain \"@\"","blank":"can't be blank"}}]"
id="user_email"
name="user[email]"
placeholder="[email protected]"
type="email" value="[email protected]">
Any idea what the issue might be?
I don't understand why I get the message Request error: 0
when I submit a valid form. All fields are valid but when I send the form then the field becomes invalid with this message while the form is sent. The form is sent correctly, it's just the client side validation that does that for one second.
If I take a look to the sent request,
Request URL:http://www.holdsport.dev:3000/validate?klass=club&attribute=name&value=teste&kind=uniqueness
Request Headers CAUTION: Provisional headers are shown.
Accept:application/json
Referer:http://www.holdsport.dev:3000/signup/new_club
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.152 Safari/537.36
X-Requested-With:XMLHttpRequest
Query String Parametersview sourceview URL encoded
klass:club
attribute:name
value:teste
kind:uniqueness
That's all, no preview, no response from server. But the uniqueness works well otherwise.
Any idea?
I'm assuming it's an intentional design decision to not include this in the library, but I think it would be incredibly useful to folks (and drive adoption of the library) to at least include a basic example of how to do this. I understand the impetus for keeping judge lightweight and minimal, but since the $(form).validate() method shouldn't really differ between applications, I see no reason to not include it.
FWIW, here's my naive implementation:
(($, window) ->
class FormValidator
ERROR_CLASS = 'error'
defaults: {}
constructor: ($el, options) ->
@$el = $el
@options = $.extend({}, @defaults, options)
@bindEvents()
bindEvents: ->
@$el.on 'blur', '[data-validate]', (e) => @validateInput(e.currentTarget)
@$el.on 'input', '[data-validate].error', (e) => @validateInput(e.currentTarget)
@$el.on 'submit', @validateAll
validateAll: (e) =>
$(e.currentTarget).find('[data-validate]').each (_, el) => @validateInput(el)
if $(e.currentTarget).find('[data-validate].error')[0]
e.stopPropagation()
e.preventDefault()
validateInput: (el) =>
judge.validate(el, { valid: @_valid, invalid: @_invalid })
_valid: (el) =>
@getMsgItem(el)?.remove()
$(el).removeClass(ERROR_CLASS)
_invalid: (el, messages) =>
@findOrCreateMsgItem(el).text(messages.join(', '))
$(el).addClass(ERROR_CLASS)
findOrCreateMsgItem: (el) ->
if (x = @getMsgItem(el))
x
else
$item = $("<div class='error_message' />")
$item.insertAfter($(el))
$item
getMsgItem: (el) ->
if (x = $(el).parent().find('.error_message'))[0]
x
else
null
$.fn.extend addFormValidation: (option, args...) ->
@each ->
return unless $(@).find('[data-validate]')[0]
data = $(@).data('form-validator')
if !data
$(@).data 'form-validator', (data = new FormValidator($(@), option))
if typeof option == 'string'
data[option].apply(data, args)
) window.jQuery, window
$ ->
$('form').addFormValidation()
In my user
model I have the following:
validates_acceptance_of :terms_accepted, allow_nil: false
validates_acceptance_of :data_terms_accepted, allow_nil: false
But I can submit the form without checking the checkboxes. I guess that this feature is not implemented.
By the way, thanks for the support, really appreciated.
Great gem that you have shared with us!
I am having some problems validating the email
attribute in my User
model. I am using devise
's validatable module to perform validation of the uniqueness of the email
as well as some regex validations I guess.
When using judge
on my form, I get back this 'is invalid' error when I enter any email into my form.
Any idea why this is?
My initializer:
Judge.configure do
expose User, :email
end
My js:
judge.validate document.getElementById("user_email"),
valid: (element) ->
console.log "Good job"
invalid: (element, messages) ->
console.log messages.join(', ')
My form:
= form_for(resource, :builder => Judge::FormBuilder, :as => resource_name, :url => registration_path(resource_name)) do |f|
= f.text_field :email, :validate => true
My log:
Started GET "/judge?klass=user&attribute=email&value=my%40email.com&kind=uniqueness" for 127.0.0.1 at 2014-06-03 18:44:37 +0200
Processing by Judge::ValidationsController#build as JSON
Parameters: {"klass"=>"user", "attribute"=>"email", "value"=>"[email protected]", "kind"=>"uniqueness"}
Completed 200 OK in 5ms (Views: 0.2ms)
And when I remove the validatable module from my User
model, no errors are returned.
I use a custom script to bind events and run the validation client side dynamically.
https://github.com/Vadorequest/judge-bootstrap3-helper
Here is the problem:
It looks like if we perform Ajax validation (uniqueness) the 'uniqueness' rule is applied before the 'required' rule and because the required rule seems to be waiting for the 'uniqueness' rule response then the ajax response (network latency) is received after the form was sent, because there is no errors at the time (in the DOM) the error is generated after. But the form was considered as valid and sent.
This happens when there is only the uniqueness validation to run and no other validation.
So I'm looking for a workaround/fix about that, because the user could just click on send
and the form would be sent, thinking there is no errors while the Ajax request is in process. It's a special case because if there is another input that fails at the validation then it works fine, also, if the validation is performed before (blur/input events)to click on the send
button then the validation fails (required) and the form is not send.
Of course, the issue is strongly linked to the way my script works, I'm asking if there is a way to fix this by maybe run validation such as required
before uniqueness
or another workaround.
Thanks.
Hi Joe,
This is kind of super weird.
I follow your suggestions to add a custom validation (it is an asyncronous validator - need to perform a call to the server in order to check the presence of a specific parameter in a model).
What is weird is that without the custom validator, all the other standard validator present on the model work as a charm, instead when i include my custom validator, it just run it and not more the standard validator.
Maybe I am doing something very wrong, and I need some clarifications or help about it.
The follow are the step that I did:
(1) Created my custom validator in rails (it works fine I tested it on the server side).
(2) Added uses_messages :validator_error_name to use the i18n with judge
(3) Created my custom validator client side (I put it in a js file called judge-extensions, and I included it in my app.js after judge) 👍
judge.eachValidators.user_existence = function() {
// create a 'pending' validation
var validation = new judge.Validation();
$.ajax(judge.urlFor(this, 'user_existence')).done(function(messages) {
// You can close a Validation with either an array
// or a string that represents a JSON array
validation.close(messages);
});
return validation;
};
(4) I added the expose Model, :parameter in the config for the judge
(5) I added my custom validator to my model
validates :email, presence: true,
format: {with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i},
user_existence: true
Now When I run my code, I see that the custom validator is called, and it works fine (gives error when it need to give error, and give valid when need to be valid).
This means that the code is right, except that it become the only validation that runs.
I mean with my custom validation, format and presence are completely ignored (are not performed at all, like are not present in the model).
If I comment out in the model the custom validator, then the other two are automatically working again.
What I am doing wrong? Because I am doing something wrong for sure.
Thanks so much
Best
Dinuz
I'm thinking that using Judge to validate Backbone.js models would actually be pretty easy and really nice to have. Possibly as a extension so that people who don't use Backbone don't have to load it...
Does it work? My empty text input after blur, fails validation.
I´m using the gem 'validates_timeliness' in a project. In this project I have a validation like this:
validates :fechafin, presence: true
validates_date :fechafin, :after => :fechainicio,
:after_message => "debe ser mayor o igual que la fecha de inicio"
where 'fechainicio' is another field of the model.
And judge gem generates validators like this:
<input class="form-control" data-validate="[{"kind":"presence","options":{},"messages":{"blank":"Por favor, rellena la fecha de fin"}},{"kind":"timeliness","options":{"after":"fechainicio","after_message":"debe ser mayor o igual que la fecha de inicio"},"messages":{}}]" type="text">
How i could mark the "validates_date" validation? I have test with this line but doesn´t works:
validates_date :fechafin, :judge => ignore, :after => :fechainicio,
:after_message => "debe ser mayor o igual que la fecha de inicio"
Due to various circumstances, I haven't had enough time or energy in the past year to give this gem the attention it deserves. I no longer use it in my day job, so there is no potential for paid maintenance going forward.
Judge is – as far as I can tell – the most widely-used client-side validation gem around these days, at least in terms of projects that are still actively maintained. If you'd like to help me out in any way, I would really appreciate it. I know there are enough of you out there to share the load. :)
I'd love to give commit access to a handful of people. We could even move the project to its own org, if there's any advantage to doing so. New maintainers would need to:
Please reply here if you're interested! I'm especially keen to hear from people who use Judge already, but that doesn't have to be the case. I think Judge is quite a simple project despite the fact that it bridges the client-server gap. If you're relatively new to Rails, helping out with maintenance might be a good way to improve your Ruby or JavaScript skills. Beginners, consider yourselves very welcome. :)
This does not work for me (Rails 3.2.2 on JRuby, with Judge 2.0.4).
Judge.configure do
expose Post, :title, :body
end
Instead, I have to do:
Judge.configure do
expose Post, :title
expose Post, :body
end
The devise email regexp does not validate emails with successive dots e.g [email protected] gets saved.
Hello,
i love the gem thank you for making it its exactly what i needed.I am using authlogic gem and the email address of the users is validated by it, in ruby the regex for it its working fine but in javascript the judge its removing the insensitive modifier and the validation its always invalid.This is the expression "/^[A-Z0-9_.&%+-']+@(?:[A-Z0-9-]+.)+(?:[A-Z]{2,13})$/i", if you can give me some workaround it will be appreciated.The second problem is when i add expose attributes into the judge initializer my l18n config is reset to english when i have set the default locale to bulgarian.
For validations like so:
validates :title, length: {in: 3..200}, allow_blank: true
When validating inputs like this:
judge.validate(input, validHandler, invalidHandler), if the input is left empty, none of the handlers are called. The validHandler should be called in order to be able to clean up the input. Is there any workaround?
Hi! Another regex issue :)
Here is my regex, in the model:
validates :email, format: { with: /\A\s*(([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})[\s\/,;]*)+\Z/i }
Here is the generated data-validate
attribute on the view.
data-validate="[{"kind":"presence","options":{},"messages":{"blank":"skal udfyldes"}},{"kind":"format","options":{"with":"(?i-mx:\\A\\s*(([^@\\s]+)@((?:[-a-z0-9]+\\.)+[a-z]{2,})[\\s\\/,;]*)+\\Z)"},"messages":{"invalid":"er ikke gyldig","blank":"skal udfyldes"}}]"
I'm not a pro in regex but it looks like the \
is doubled due to some conversion. And obviously the regex doesn't works with valid emails.
[1] pry(main)> JSON.dump(:with => /abc/)
=> "{\"with\":\"(?-mix:abc)\"}"
Any work around?
Thanks.
Hi, I'm trying to understand why in this special case, neither my method _valid
and _invalid
are called once the validation is executed.
When I have an input that have a regex such as:
validates :mobile, format: { with: /^(\W*\d){6,10}\W*$/ }, allow_blank: true
If I type a character in the input and if I delete it (empty input) my view is not updated, still red. https://docs.google.com/file/d/0ByzbHcAxmCyvWWI1c1kzbDF4YlE
Of course there is more than judge.js
to do so, here is the script managing the view update: https://github.com/Vadorequest/judge-bootstrap3-helper/blob/master/js/judge.js
I tried some things and here is what I'm sure:
_valid
/_invalid
are called (tried to log at the first line for both)So, I don't get it because my log line 217 is correctly executed and displays the good value, but the trigger doesn't work.
Any idea?
I don't know why and what's cause this bug, but one of my form fails at the validation basically because I got a javascript error.
Uncaught SyntaxError: Unexpected token /
At judge.js:194:
var ValidationQueue = judge.ValidationQueue = function(element) {
this.element = element;
this.validations = [];
this.attrValidators = root.JSON.parse(this.element.getAttribute('data-validate'));
...
The form email input.
<input class="string email required form-control" data-validate="[{"kind":"presence","options":{},"messages":{"blank":"skal udfyldes"}},{"kind":"format","options":{"with":/^\s*(([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})[\s\/,;]*)+$/i},"messages":{"invalid":"er ikke gyldig","blank":"skal udfyldes"}}]" id="user_email" name="user[email]" size="50" type="email" value="">
I think you're missing something with custom regex validation converted into json, looks like something should be protected to avoid this behavior.
The documentation in the readme is good enough for people to understand the purpose of the library and how to use it, however the code itself is largely without documentation and this might be putting off potential contributors / bug reporters.
I suggest YARD unless anyone has a better idea. Thoughts, anyone?
To get client side validation to work, I have to set :validate => true
for each form field I want to be validated on the client side. In addition I have to also write javascript for each input and how it should be validated.
This seems to be against the whole point of trying to avoid duplication between server side validation and client side validation. If my model says something is required, by default I would expect it to be validated on the client side without have to write a ton of code. Curious to your reasoning for the current implementation and if maybe I am missing something.
Thanks for all your work!
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.