How can I validate a text_field_tag?

Hey people,

I was wondering whether it's possible to validate a text_field_tag which has nothing to do with the actual object being created?

Thanks

Hey people,

I was wondering whether it's possible to validate a text_field_tag which has nothing to do with the actual object being created?

validations are by definition a model centric thing. However there's nothing stopping you doing if not_good(params[:some_text:])   ... else   @record.save end

Fred

you could also try...@record.is_valid?

which will validate w/o saving

Heinz Strunk wrote:

Hey people,

I was wondering whether it's possible to validate a text_field_tag which has nothing to do with the actual object being created?

Thanks

What about JavaScript? For example, I call a Vlaidation method onsubmit with a form when somebody creates a new object. Just a thought.

-S

Hey,

both are actually pretty good approaches I think but I was hoping I could use that could use error_messages_for for the text_field_tag... that's probably not the case? If I was using "if not_good(params..." I'd need to display it differently. It'd be extremly handy if I could just add an error to error_messages_for using "if not_good(..."

Hey,

both are actually pretty good approaches I think but I was hoping I could use that could use error_messages_for for the text_field_tag... that's probably not the case? If I was using "if not_good(params..." I'd need to display it differently. It'd be extremly handy if I could just add an error to error_messages_for using "if not_good(..."

You can call some_object.errors.add(...) to add errors to an activerecord object (you probably need to make the validations run first). Check out the errors class in the api.

Fred

But the text_field_tag has nothing to do with the @record so it wouldn't help if I was checking if the @record is valid, right?

tony wrote:

Heinz,

If you’re looking to invalidate the object based on this non-member field, you could use ActiveRecord.Errors.add_to_base()

e.g. @record.errors.add_to_base(“Invalid unpopple value”)

Then check validity with @record.errors.empty?

Note that @record.is_valid will still return true (unless you override invalid? for the class).

Hope that helps,

James.

since your text field tag isn't part of the model, you could instantiate the object with the value from the tag and then call is_valid and check the errors variable if you want the message. else you'll have to write your own validation methods

Very nice. Very helpful. Thank you, James.

Best regards, Bill