1

I need to set three different types of allowed inputs for my application like this:

  • running disciplines 00,00
  • long running disciplines 00:00,00
  • jumping disciplines 0,00

<%= f.text_field %> should force an input such as that, is there a way I could do it?

Xeen
  • 6,955
  • 16
  • 60
  • 111
  • 3
    Have a look at [jQuery Mask Plugin](http://igorescobar.github.io/jQuery-Mask-Plugin/) for masking input fields. Back this by model format validation on those fields. – vee Apr 26 '14 at 14:29

2 Answers2

0

One way can be to use JS functions, put all the validations in that, and show alerts when user tries to submit the form. Js function will be like this:

function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
if (x==null || other conditions)
  {
  alert("Please enter in THAT format");
  return false;
  }
}

and using following HTML snippet, you can validate it on submit:

<input type="submit" value="Submit" onsubmit="return validateForm()">

Check this as well.

Community
  • 1
  • 1
Saurabh
  • 71,488
  • 40
  • 181
  • 244
  • I thought about this aswell, but got stuck at figuring out how to define `00:00,00` to be the right format :) – Xeen Apr 26 '14 at 14:19
  • You can test this format using a regular expression like `/^\d{2}:\d{2},\d{2}$/.test(x)` – Brian Glick Apr 26 '14 at 14:36
0

Yes you can do it with Model validation along with a Regular Expression. So if you are only allowing the given values i.e., '00,00', '00:00,00', '0,00' , you can do:

class ModelName < ActiveRecord::Base
    validates_format_of :field_name, :with => /((\A[0]{2}(\,|\:)[0]{2}((\,)[0]{2})*\Z)|(\A[0]{1}(\,)[0]{2}\Z))/i, :message => " is Invalid"
end

Check it here http://rubular.com/r/7ZGo0ktlSe

Update as per the comment from Xeen:

If you allow all the digits [0-9], the you can go for the answer below:

class ModelName < ActiveRecord::Base
    validates_format_of :field_name, :with => /((\A\d{2}(\,|\:)\d{2}((\,)\d{2})*\Z)|(\A\d{1}(\,)\d{2}\Z))/i, :message => " is Invalid"
end

Check http://rubular.com/r/c2Q5K3armn.

Hope it helps :)

Rajesh Omanakuttan
  • 6,788
  • 7
  • 47
  • 85
  • This doesn't seem to be working, it allows only literaly `00,00`, but if it's, say, `15,22` the it doesn't let it through – Xeen Apr 26 '14 at 17:31
  • @Xeen: You did not say what all character types you want to allow with the given format. That's why I've considered `00,00` only and not `15,22`. – Rajesh Omanakuttan Apr 27 '14 at 03:16