[Java] Click the [rails] button to create a random alphanumeric password and enter it in the password field

1 minute read

I want to automatically generate a password

I set a password function for the portfolio posting function, It would be convenient if there was a function that automatically generated and entered a password.

Let’s make it!

Goal of this article

Click the “generate password” button Let’s input it automatically! Password generation.gif

Assumption

rails:5.2 ruby:2.6.3 bootstrap jquery

Generate password

First, let’s make random alphanumeric characters with the controller.

topics_controller.rb


def new
  @topic = Topic.new
  @password = SecureRandom.alphanumeric(6)
  -> Generate random alphanumeric characters (A-Z, a-z, 0-9)
   (6) is 6 digits, 16 digits if not specified
end

Allow to fill in the field with the click of a button

Next, set the password you created earlier to password_field (this time it is text_field) Allows you to enter.

ruby:new.html.erb


<div class="topic-new-wrapper">
  <div class="container">
    <div class="row">
      <div class="col-md-6 col-md-offset-3">
          <%= form_for @topic do |f| %>
            <div class="form-group">
              <%= f.label :password,'password (optional)' %>
              <%= f.text_field :password, class:'form-control', id:'password' %>
              <%= button_tag'Generate password', id:'auto-fill-link' %>
            </div>
  
            <%= f.submit'password registration', class:'btn btn-black btn-block' %>
  
          <% end %>
      </div>
    </div>
  </div>
</div>
  
<script>
  $(function(){
    autoFill();
    function autoFill() {
      $('#auto-fill-link').click(function(){
        $('#password').val("<%= @password %>");
      });
    }
  })
</script>

When a link containing the id “auto-fill-link” is clicked, it contains the id “password” @password is entered in the field.

However, if it is this, it will be submitted when the button_tag is clicked, When using it as a button, add the following code.

type: “button”

ruby:new.html.erb


<div class="topic-new-wrapper">
  <div class="container">
    <div class="row">
      <div class="col-md-6 col-md-offset-3">
          <%= form_for @topic do |f| %>
            <div class="form-group">
              <%= f.label :password,'password (optional)' %>
              <%= f.text_field :password, class:'form-control', id:'password' %>
This line -> <%= button_tag'Generate password', id:'auto-fill-link', type: "button" %>
            </div>
  
            <%= f.submit'password registration', class:'btn btn-black btn-block' %>
  
          <% end %>
      </div>
    </div>
  </div>
</div>
  
<script>
  $(function(){
    autoFill();
    function autoFill() {
      $('#auto-fill-link').click(function(){
        $('#password').val("<%= @password %>");
      });
    }
  })
</script>

Summary

We have created a function that allows you to create and enter a password.

It’s easy, so please use the code above.