Rails foundationSort Order

Rails: Model Validation

In this episode we discuss the importance of valdiation, and we show you an example of how we can use it in our application. One of the most simple example we can illustrate is the email validation for the user model.

class User < ActiveRecord::Base  # ...    validates :email, format: { with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i }end

Let's try out our validation

user = User.first# This will workuser.email = "zack@codemy.net"user.save# This won'tuser.email = "invalid@email"user.save

We can also try creating a new user with invalid email. It will use the supplied regex to validate the email. Now that we have a case where user registration can fail we need to handle the error in our user controller.

class UsersController < ApplicationController  # ...    def create    @user = User.new(user_params)    if @user.save      redirect_to root_path    else      # handle the error by rendering the form.      render :new    end  end    # ...end

There are many kinds of validation head over to this link for a full list. ActiveModel Validations