0

Using Devise with Rails 4

I would like my email_field to have a red border until the user inputs an email in a valid format, then it would change to green.

I am having trouble finding documentation on doing this so if you can recommend the best way to go about this, that would be awesome.

My current view:

<div class="form-group">
  <%= f.email_field :email, placeholder: 'Email', :autofocus => true, class: 'form-control' %>
</div>

user.rb:

devise :database_authenticatable, :registerable,
       :recoverable, :rememberable, :trackable, :validatable, :omniauthable

and if there is already documentation on this, can you please point me in that direction. Thank you!

Kathan
  • 1,428
  • 2
  • 15
  • 31

2 Answers2

1

You need to add a custom validation on the front end using Javascript. The validation would simply require you to add a certain class to the email field once the validation is correct. You can use the following regex for the email validation. This is just an example and you should look up RFC standards to see valid emails and modify the regex accordingly.

function validateEmail(email) {
    var re = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
    return re.test(email);
}

For the sake of convenience, we assume the text field looks something like this:

<input type="text" id="subEmail" onchange="checkFilled();">

Now, we need a function that gets the value from the input field, validates it using our function, and assigns the appropriate class to the field.

function checkFilled() {
    var inputVal = document.getElementById("subEmail").value;
    if (validateEmail(inputVal)) {
        document.getElementById("subEmail").className = "valid"
    }
    else{
        document.getElementById("subEmail").className = "invalid"
    }
}
checkFilled();

Here's the necessary CSS:

.invalid {
    border:1px solid red
}
.valid {
     border:1px solid green
}

Here's a working fiddle.

Sid Shukla
  • 990
  • 1
  • 8
  • 33
1

This can't be done in rails, it needs to be done in javascript or jQuery.

Create a javascript function that validates the email... see the accepted answer in this SO question for how to make that function.

Validate email with jQuery

Then change the class of the email input if it's valid, something like this (untested though)...

$( '#user_email_field' ).bind('input', function() {
  if ( validateEmail( $( '#user_email_field' ).value ) ) {
    $( "#user_email_field" ).addClass('valid').removeClass('invalid');
  }
  else {
    $( "#user_email_field" ).removeClass('valid').addClass('invalid');
  }
});

Specify in your css the color of the field border for the 'valid' and 'invalid' classes.

Community
  • 1
  • 1
SteveTurczyn
  • 36,057
  • 6
  • 41
  • 53