0

I am trying to do some form validation in my Ruby on Rails app using Coffeescript. However the script isnt executing. I am trying to add a validation to check if password entered and confirmation password entered are equal.

$(document).on 'ready page:load', ->
  password = document.getElementById('user_password').value
  password_confirmation = document.getElementById('user_password_confirmation').value

  validatePassword = ->
    password = document.getElementById('user_password').value
    password_confirmation = document.getElementById('user_password_confirmation').value
    if password.value != password_confirmation.value
      password_confirmation.setCustomValidity 'Passwords Don\'t Match'
    else
      password_confirmation.setCustomValidity ''
    return

  password.onchange = validatePassword
  password_confirmation.onkeyup = validatePassword

I added $(document).on 'ready page:load' as mentioned in this post but it does not seem to have any effect.

My corresponding .html.erb file contains the following code:

<%= f.password_field :password,:onkeyup => 'validatePassword()', class: 'form-control',:required=>true %>
<%= f.password_field :password_confirmation, :onkeyup => 'validatePassword()', class: 'form-control',:required=>true %>
Community
  • 1
  • 1
user1692342
  • 5,007
  • 11
  • 69
  • 128
  • Are you sure this coffescript files in included in your assets pipeline? is it included in the page source? and do you get any errors in the browser's console? – bigsolom Sep 24 '15 at 09:19
  • @bigsolom yes it's in my asset folder. The JavaScript file is present once the page loads as well. No error on console – user1692342 Sep 24 '15 at 11:15

1 Answers1

0

are you sure the script is not run? Did you put console.log in your $(document).on 'ready page:load' callback and check it?

next thing... I believe it won't work even if script is executed. When defining validatePassword function within page:load callback you don't assign it to window object. What happens here is just a creation of local function within callback that is unreachable from outside (validatePassword() in your erb file). you should write window.validatePassword = ...definition...

one more thing. This line password = document.getElementById('user_password').value returns a value, which is String. A few lines later you're writing password.onchange = validatePassword, but problem is password doesn't have onchange property (because it's a String). What you probably wanted to achieve here is password = document.getElementById('user_password')

djaszczurowski
  • 4,385
  • 1
  • 18
  • 28
  • I corrected the value part in getElementById. I checked chrome debugger and it is following the expected path. However the message set in setCustomvalidity is not executing..I think it is related to the window you mentioned. However I am not able to follow it – user1692342 Sep 24 '15 at 22:19