.

How to use an auto_complete to validate passwords

As a follow up to my previous article about using auto_completes to ensure unique filenames, I’ve put together a bit of code that does essentially the same thing except that it checks a password field to ensure that it meets certain criteria.

  1. # view file
  2. <%= text_field_with_auto_complete :user, :password %><div id=login_error></div>
  3.  
  4. # model file
  5.  
  6. def User < ActiveRecord::Base
  7.   validates_length_of :password, :in=>3..20
  8. end
  9.  
  10. # controller file
  11.  
  12. def auto_complete_for_user_password
  13.   @user = User.new(params[:user])
  14.   @user.valid# ensures the errors array is populated
  15.   password_errors = @user.errors.on(‘password’)
  16.   render :update do |page|
  17.      page.replace_html ‘login_error’, (password_errors.empty? ? "" : password_errors)
  18.    end
  19. end

This will indicate when a password does not meet the validation criteria defined in the model. You can add custom validations to check the strength of the password itself.

No comments yet. Be the first.

Leave a reply