Simple Ruby Input Validation Library
You could use ActiveModel::Validations, from Rails 3 RC:
require 'active_model'
# this appears to be a bug in ActiveModel - it uses this, but does not require it
require 'active_support/core_ext/hash'
class Model
include ActiveModel::Validations
attr_accessor :name
validates_presence_of :name
end
m = model.new
puts m.valid? # false
m.name = "John Doe"
puts m.valid? # true
Is there a lightweight, all purpose validation library/DSL for Ruby?
I think standalone ActiveModel should be good for this.
Watch this railscast for more information: http://railscasts.com/episodes/219-active-model
Clean way to implement validation on non-crud routes in Rails?
The solution here was never really a custom validator - instead you should create a class such as a model or form object to encapsulate the validations and data. Just because your action doesn't persist anything doesn't mean you can't use a model to represent data and buisness logic.
class RecipeSearch
include ActiveModel::Model
include ActiveModel::Attributes
attribute :query, :string
attribute :sort_by, :string
# ...
validates :query, length: { minimum: 5 }
validates :sort_by, in: ['newest', 'quickest', 'cheapest']
# ...
# @todo apply filters to Recipe and return collection
def perform
# ...
end
end
This lets you add validations and logic. And pass it to forms:
<%= form_with(model: local_assigns(:recipe_seach) || RecipeSearch.new) do |f| %>
# ...
<% end %>
Its also a misconception that searching can't be a part of CRUD. It is after all just Read with filters applied. If you really need a separate view from your normal index then by all means create a separate search action but its not really a neccissity.
class RecipesController
def index
@recipe_search = RecipeSearch.new(search_params)
@recipes = @recipe_search.perform
end
private
def search_params
params.fetch(:recipe_search, {})
.permit(:query, :sort_by)
end
end
The rails way of doing client side validation (Rails 4 with simple_form)
There is client_side_validations, but is not longer maintained. Probably the best way is using some jQuery plugin like jquery-validation.
Ruby library with least footprint to host a very simple single endpoint API
You seem like you want to use Rack directly. "Rack from the Beginning" is a decent tutorial that should get you started.
It'll probably look something like this:
class CrunchApp
def self.crunch(crunchable)
# top-secret crunching
end
def self.call(env)
crunchy_stuff = input(env)
[200, {}, crunch(crunchy_stuff)]
end
private
def self.input(env)
request = Rack::Request.new(env)
request.params['my_input']
end
end
Rack::Server.start app: CrunchApp
But I must say, using that instead of something like Sinatra seems silly unless this is just a fun project to play with things. See their 'Hello World':
require 'sinatra'
get '/hi' do
"Hello World!"
end
Email validation in Ruby on Rails?
I use the constant built into URI in the standard ruby library
validates :email, format: { with: URI::MailTo::EMAIL_REGEXP }
Ruby Email validation with regex
TL;DR:
credit goes to @joshuahunter (below, upvote his answer). Included here so that people see it.
URI::MailTo::EMAIL_REGEXP
Old TL;DR
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i
Original answer
You seem to be complicating things a lot, I would simply use:
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z/i
which is taken from michael hartl's rails book
since this doesn't meet your dot requirement it can simply be ammended like so:
VALID_EMAIL_REGEX = /\A([\w+\-]\.?)+@[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z/i
As mentioned by CAustin, there are many other solutions.
EDIT:
it was pointed out by @installero that the original fails for subdomains with hyphens in them, this version will work (not sure why the character class was missing digits and hyphens in the first place).
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i
Rails: What's a good way to validate links (URLs)?
Validating an URL is a tricky job. It's also a very broad request.
What do you want to do, exactly? Do you want to validate the format of the URL, the existence, or what? There are several possibilities, depending on what you want to do.
A regular expression can validate the format of the URL. But even a complex regular expression cannot ensure you are dealing with a valid URL.
For instance, if you take a simple regular expression, it will probably reject the following host
http://invalid##host.com
but it will allow
http://invalid-host.foo
that is a valid host, but not a valid domain if you consider the existing TLDs. Indeed, the solution would work if you want to validate the hostname, not the domain because the following one is a valid hostname
http://host.foo
as well the following one
http://localhost
Now, let me give you some solutions.
If you want to validate a domain, then you need to forget about regular expressions. The best solution available at the moment is the Public Suffix List, a list maintained by Mozilla. I created a Ruby library to parse and validate domains against the Public Suffix List, and it's called PublicSuffix.
If you want to validate the format of an URI/URL, then you might want to use regular expressions. Instead of searching for one, use the built-in Ruby URI.parse
method.
require 'uri'
def valid_url?(uri)
uri = URI.parse(uri) && uri.host
rescue URI::InvalidURIError
false
end
You can even decide to make it more restrictive. For instance, if you want the URL to be an HTTP/HTTPS URL, then you can make the validation more accurate.
require 'uri'
def valid_url?(url)
uri = URI.parse(url)
uri.is_a?(URI::HTTP) && !uri.host.nil?
rescue URI::InvalidURIError
false
end
Of course, there are tons of improvements you can apply to this method, including checking for a path or a scheme.
Last but not least, you can also package this code into a validator:
class HttpUrlValidator < ActiveModel::EachValidator
def self.compliant?(value)
uri = URI.parse(value)
uri.is_a?(URI::HTTP) && !uri.host.nil?
rescue URI::InvalidURIError
false
end
def validate_each(record, attribute, value)
unless value.present? && self.class.compliant?(value)
record.errors.add(attribute, "is not a valid HTTP URL")
end
end
end
# in the model
validates :example_attribute, http_url: true
Rails - Setting custom validation messages for input field(front-end)
I am adding my answer - how to use the wonderful jquery.validate library for client side validation.
I am using version 1.13.1
Here it goes..
Download the library and place it in
app/assets/javascripts/jqueryValidation/dist
folder which includesadditional-methods.min.js
andjquery.validate.min.js
.Add the library in your asset pipeline so that its available globally.
//= require jqueryValidation/dist/jquery.validate
//= require jqueryValidation/dist/additional-methodsstart using the library on the form in your
_form.html.erb
.<%= form_for(@new,:html=>{:id=>"newForm") do |f |%>
//input fields with text/number/textarea etc
<%end%>initialize the script and validate the form input fields.
$("form#new_form").validate({
//use this to ignore autocomplete fields present,if any
ignore: "",
//set rules for input elements using name attribute
rules: {
"new_form[address]": "required",
"new_form[tag]": "required",
"new_form[title]": {
required: true,
minlength: 3,
maxlength: 100
},
"new_form[contact_email]": {
required: true,
email: true,
minlength: 5,
maxlength: 100
},
"new_form_photos[avatar][]": {
required: true,
extension: "jpeg|jpg|png|gif"
},
//use this to show custom dedicated placeholder message everytime validation fails...just like dynamic alert
errorPlacement: function(error, element) {
$("#show_error").html("<span class='text-danger' >Fields marked with * are required</span>");
},
//use this callback to get which field is currently failing validation and then add more custom logic if needed
//for eg: you want to update the color of name label if validation fails.
//validator.errorList contains an array of objects, where each object has properties "element" and "message". element is the actual HTML Input.
invalidHandler: function(e,validator) {
//use the key value pair to get => id=new_form_title, to identify your input field
for (var i=0;i<validator.errorList.length;i++){
console.log(validator.errorList[i].element.attributes['id'].value);
if ( validator.errorList[0].element.attributes['id'].value == "new_form_tag"){
//handle tag input field here by adding css/alert/focus etc
}
}
}
});//validation ends
Similarly, we have submitHandler: function(form) {}
,onkeyup: function (element, event) {)
Hope it helps. :)
Related Topics
Rubocop Error 'Class Definition Is Too Long Ruby'
Gem::Ext::Builderror: Error: Failed to Build Gem Native Extension Bcrypt-Ruby
Ruby on Rails: /Bin/Sh: Rspec: Command Not Found
Including/Extending the Kernel Doesn't Add Those Methods on Main:Object
@Instance_Variable Not Available Inside a Ruby Block
Ruby Symbols VS Strings in Hashes
Error Occurred While Installing Mini_Racer (0.2.0)
Why I Can Not Call Super in Define_Method with Overloading Method
Ruby: How to Store and Display a Day of the Week
Heroku: No Rakefile Found (But Works Locally)
Displaying Only the First X Words of a String in Rails
Convert String to Class Name Without Using Eval in Ruby
How to Get My Aws Lambda to Access Gems Stored in Vendor/Bundle
How to Use a Branch in a Fork of Rails in a Project with Bundler
Getting Devise Sign_In Form into Twitter Bootstrap Modal
How to Define a Ruby Singleton Method Using a Block
How to Access Firefox Extension I Added in Selenium Webdriver