Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I encountered this same problem and after reading this post I implemented the code suggested by apneadiving in his answer but with a slight modification:</p> <p>I used two different validations, one for create:</p> <pre><code>validates :password, :presence =&gt; true, :confirmation =&gt; true, :length =&gt; { :within =&gt; 6..128 }, :on =&gt; :create </code></pre> <p>and then I used this one for update:</p> <pre><code>validates :password, :presence =&gt; true, :confirmation =&gt; true, :length =&gt; { :within =&gt; 6..128 }, :on =&gt; :update, :unless =&gt; lambda{ |user| user.password.to_s.empty? } </code></pre> <p>Originally, I Implemented exactly what apneadiving suggested, but I realized that on updates to the user it wasn't actually validating the presence of a string. As in, it was allowing a user to set their password to <code>" "</code> (A string of whitespace). This is due to the fact that <code>" ".blank? == true</code>, and so if you have it set to validate like this:</p> <pre><code>:unless =&gt; lambda { |user| user.password.blank? } </code></pre> <p>Then it won't run the validation if a string full of whitespace is submitted by the user is submitted because it reads the string as being blank. This essentially invalidates the effect of validating for presence on the update. The reason I did <code>password.to_s.empty?</code> instead of simply <code>password.empty?</code> is to prevent errors if someone calls update_attributes on the user model and doesn't pass in anything into the password, field, then the password will be <code>nil</code>, and since the ruby <code>nil</code> class doesn't have an empty? method, it will throw an error. Calling <code>.to_s</code> on <code>nil</code>, however will convert it to an empty string, which will return true on a successive <code>.empty?</code> call (thus the validation won't run). So after some trials and tribulation I found that this was the best way to do it.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload