For acts-as-taggable-on, how do you make Tags be a certain amount of characters? I want users to only be able to have a maximum of 50 characters when they are creating tags.
Thank you.
You can use a validation for this. Try using this in your model. Replace :tag_name with the correct field.
validates_length_of :tag_name, :maximum=>50
Also an awesome reference to rails validations is here.
Related
I defined a custom EachValidator to see if an attribute has leading or trailing whitespace. I know you can add it to the model like so:
validates :name, whitespace: true
But in the controller I want to call just run just the whitespace validator for some form feedback.
I can run it like this:
Validators::WhitespaceValidator.new(attributes: :name).validate_each(obj, :name, obj.name)
Is there a shorter way to call the specific validator? Like you can do user.valid? but that runs all of the validations. I only want the whitespace validator on the name attribute.
Since you did not come here to be told that your idea is bad and people will hate it: here is an idea that you can play with: :on
https://guides.rubyonrails.org/active_record_validations.html#on
validates :name, whitespace: true, on: :preview
and then in the controller:
def something
#model.valid?(:preview)
end
If you want to run the validation also on createand update you can specify something like
on: [:create,:update,:preview]
(Thanks engineersmnky)
Also: I don't think that giving early feedback to users, before they actually save the record is a bad idea if properly implemented.
This feels like trying to solve a problem (leading/trailing whitespace) by creating a new problem (rejecting the object as invalid), and I agree with the comment about this being a brittle strategy. If the problem you want to solve here is whitespace, then solve that problem for the specific attributes where it matters before saving the object; check out
Rails before_validation strip whitespace best practices
I'm implementing a comment section on my blog and was wondering if there was a way to prevent users from submitting a name such as admin or [company name] to prevent people from trolling or otherwise wrong-doing.
I am using this REGEX to validate emails making sure they are properly formatted: VALID_EMAIL_REGEX = /\A[\w+\-.]+#[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i
I'm just not sure if this is the same approach I need to be taking or if there are built in ways to prevent specific strings from being entered into a form input.
Thanks in advance for any help!
There are several ways you could do this, depending on how you want your front-end to behave. The simplest way would be to do the validation in the front-end, either with simple HTML-5 form validation, or with javascript. For HTML-5 validation you can use the pattern attribute on an input type="text" (which you could use a text_field_tag to generate in rails). This attribute accepts a regex as it's value, which you could use to prevent the input of certain key-words. You can read more about this here https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Form_validation
You could also do the validation in the back-end, either in the controller directly (hard to say what exactly you need but something like as a simple example)
if (params[:my_input_form].split & bad_words_array).any?
flash[:error] = "you entered a bad word"
redirect_to the_same_page_path
end
note: the & in this context is giving the intersection of the two arrays and will return a non-empty array if there is at least one element in common between the arrays (in this case, if any of the words entered in your input are in the bad_words array).
If you want to do it in the back-end and it's more complicated I would probably move the validation into the model as a custom validator.
You can use gem obscenity. It gives you ability to specify black list words and they'll be replaces with [censored] string
An alternative to what has already been proposed is to create a custom validation on your model with a regular expression.
For example:
validate :bad_words
def bad_words
if (/admin|sony/i.match(self.name))
errors.add(:name, "contains a word not allowed")
end
end
You should generate a regular expression that suits your needs, but it is recommended to use the regexp i modifier to do a case-insensitive search
I hope it helps!
I'm getting a lot of submissions to my publicly editable site in different languages, but would like to limit it to just English characters. Is there any simple way to do this? Should I just do a validation with a regex limiting characters, or are there any common issues with that method?
Note: The text will not contain HTML or any other markup. It should just be plain text, maybe with common characters like dashes, dots, etc.
validates :comment, format: { with: [a-zA-Z0-9\s]+, on: :create } - or other action
It sounds like your problem maybe spam, so there are better solutions you can use. If this is true, see the end of this answer for details.
I commented that depends on which languages you want to block. A dozen or more languages use a latin charset, and even more use a latin charset subset. English uses accents too, such as the word naïve. So I do not recommend you try and do this.
If you must, and you want to block none-latin characters, you can write a custom validator.
class LatinCharsetValidator < ActiveModel::EachValidator
# Regex taken from this answer http://stackoverflow.com/a/13671443/276959
LATIN_CHARSET_REGEX = /[\p{L}&&[^a-zA-Z]]/
def validate_each(object, attribute, value)
object.errors.add(attribute) if value =~ LATIN_CHARSET_REGEX
end
end
You can then call this validator in your model as such:
class Comment < ActiveRecord::Base
validates :comment, latin_charset: true
end
This assumes that your users are legitimately trying to comment. If not, you can use the regex to skip the comment creation without providing feedback.
I believe this is a bad idea, though. You can't control what people end up writing or pasting in the text area, and you might end up blocking legitimate comments. What if someone wants to include a foreign word while trying to explain it? It's better to politely ask your users to only comment in English.
If your problem is spam, however, you are better off implementing a honeypot or some other type of spam protection.
I have a web-app with an location text field that has an auto complete that pulls data from Google Maps to complete the location typed in. What I want to to is force the user to choose the specific spelling and format that the auto complete gives for the location that is being typed i.o.w. a validation. The user thus can't type anything random in the location field.
I have:
validates :location, :presence => true
,but that doesn't really help. Is there a custom validation? Or one I'm not aware of?
Thanks
I guess you need to use before_validation thing like the following
before_validation do
self.location = YourClassName.find_by_location_name(location)
end
It's just an idea to get that worked. It's not an exact answer you needed.
NOT a Rails 3 issue
In a Contact model I have a company_name attribute. For reasons that don't matter to this question, I want to prohibit an ampersand character. We have a lot of clients with ampersands in their company name, and users forget they aren't allowed to use this character.
This isn't an html sanitize issue. I don't care about whitespace or CDATA or anything. The entries in this field are plain text and I don't want an ampersand to be entered in this one field in any way, shape or form.
I assume a validation on the model is the way to go. I have tried validates_exclusion_of. I have tried validates_format_of. No success. I'm unsophisticated when it comes to regex, so I might be doing things very wrong. But the bottom line is - I need to prevent a user from entering that "&" character in the company_name field.
Thanks a million.
Steve
validates_format_of :company_name, :with => /\A[^&]*\Z/
But probably you could just remove ampersands before saving record:
before_save :strip_ampersands
def strip_ampersands
company_name.gsub!("&", "")
end