开发者

Rails - Method that returns a boolean. Sometimes turns blank

I want t开发者_开发技巧o create a method that returns true or false.

Rails.logger.info is_a_valid_email?(params[:user][:email])

if is_a_valid_email(params[:user][:email]) != true
  @user.errors.add :email, 'address is not valid.'
end

protected

def is_a_valid_email?(email)

email_regex = %r{
  ^ # Start of string
  [0-9a-z] # First character
  [0-9a-z.+]+ # Middle characters
  [0-9a-z] # Last character
  @ # Separating @ character
  [0-9a-z] # Domain name begin
  [0-9a-z.-]+ # Domain name middle
  [0-9a-z] # Domain name end
  $ # End of string
}xi # Case insensitive

!( email =~ email_regex )

end

For app related reasons I need to be able to validate in the controller and no the model. The above isn't working reliably. I want 'is_a_valid_email' to either return true or false, allowing me to then apply an error msg if false.

Suggestions? thxs


You probably got a typo in your method call here:

if is_a_valid_email(params[:user][:email])

You should add a question mark there:

if is_a_valid_email?(params[:user][:email])

Also if you have to do validation in controller, you're probably doing something wrong.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜