Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Require field in form

I have an HTML form in Rails like

<form name="input" action="jump">
  Title: <input type="text" name="title"> 
  <input type="button" value="Submit">
</form> 

I want title to be a required field (i.e. the user cannot leave it blank), and I'd like to verify that in the Rails jump controller. Note that title is not a field in the model; it's just a form field that's going to be processed within the controller.

How can I do the verification, and display the error to the user elegantly?

like image 966
Mika H. Avatar asked Oct 21 '25 08:10

Mika H.


2 Answers

You can use active model to handle things:

class SomeModel << ActiveModel

#some Model
attr_accessor :title
validates_presence_of :title

end

The benefits for this is that you can throw validation and handling of displaying errors on to Rails.

The other way is to do it handling things purely on the controller side:

if  params[:title].present?

  ...#do something

else

  ...#do something else

Tis a less than elegant approach however. If you go this route, I would suggest creating a ruby object to at least moving logic out of the controller.

like image 55
sylv3rblade Avatar answered Oct 23 '25 05:10

sylv3rblade


you actually can use HTML5 tech to apply on that

 <input type="text" name="usrname" required="required" />

beside, you can use a gem 'client-side validation' the github is here https://github.com/bcardarella/client_side_validations

I suggest you use the gem...pretty awesome :D

like image 36
Nich Avatar answered Oct 23 '25 05:10

Nich



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!