November 27, 2014
Hot Topics:

Avoiding Data Corruption with Rails' Active Record Validations

  • November 12, 2007
  • By Jason Gilmore
  • Send Email »
  • More Articles »

Validating Input Length

You'll often want to validate the length of user input; for example, to ensure a password contains at least five characters. This is easily done with the validates_length_of method. For example, suppose you wanted to place a maximum limit of 500 characters for the question:

validates_length_of :message, :maximum=>500,
   :message=>"must be less than 500 characters!"

You can also place minimum limits, and even specify a range; for example, to force the user to type a message consisting of greater than 10 characters:

validates_length_of :message, :minimum=>500,
   :message=>"should be greater than 10 characters!"

Or, to momentarily deviate from the theme, suppose you wanted a registering user to create a password consisting of between 5 and 12 characters:

validates_length_of :pswd, :in=>5..12,
   :message=>"should be between 5 and 12 characters!"

Validating Format

The third of many validation methods at your disposal that I'd like to introduce is the validates_format_of method, which allows you to specify a free-form regular expression pattern that the input must successful match against for the rule to pass. This method is particularly useful for validating complex strings such as an email address:

validates_format_of :email,
   :with => /^\S+\@(\[?)[A-Za-z0-9\-\.]+\.([A-Za-z]{2,4}|
            [0-9]{1,4})(\]?)$/ix,
   :message=>"is not a valid e-mail address!"

Adding this rule will allow email addresses such as jason@example.com, jason@example.info, and jason@example.net, but disallow incorrect addresses such as jason@example, jason, and jason@.

As an exercise left to the reader, how might you go about validating the support form's phone number using validates_format_of? Remember, you'll need to take a number of variations into account; for instance, (123) 456-7890, (123) 4567890, and 123-233-2920.

Conclusion

This introductory tutorial on Rails' Active Record features can go a long way towards helping eliminate data corruption possibilities. Stay tuned for further articles exploring similar topics!

About the Author

W. Jason Gilmore is Apress' open source editor, and is co-founder of IT Enlightenment. He's the author of several books, including the best-selling Beginning PHP and MySQL 5: Novice to Professional, Second Edition (Apress, 2006. 913pp.). Jason loves receiving email, so don't hesitate to write him at wjATwjgilmore.com.





Page 3 of 3



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Sitemap | Contact Us

Rocket Fuel