-1

I want to validate a number field with regular expression -

like

REGULAR_EXPRESSION_VALUE = ?
validates :current, allow_blank: true, format: {with: REGULAR_EXPRESSION_VALUE}

which excepts postive or negative number and also floating point numbers

Examples

10 (Except)

10.15 (Except)

-10 (Except)

-10.15 (Except)

Test (Not Except)

  • why aren't you using numericality builtin validation ? http://guides.rubyonrails.org/active_record_validations.html#numericality – Manishh Apr 20 '18 at 07:03
  • I need negative or positive values as input and not string. numaricality allows only positive or only negative not both. So I need to validate with regex @Manishh – Sahidur Rahman Suman Apr 20 '18 at 07:56

3 Answers3

2

You can use the following regex to validate number or not. I am using java to write code, you can convert accordingly.

public static Boolean isNumber(String item) {
            String pattern = "^-?[0-9]\\d*(\\.\\d+)?$";
            return item.matches(pattern);
}
Ravi Sapariya
  • 395
  • 2
  • 11
1

Ravi's answer has good regex. Here it is for your code

/\A[-+]?[0-9]*\.?[0-9]+\z/

Rails prefers to use \A or \z instead of ^ or $

This is reason why

0

According to this Answer (regular expression-to allow negative and positive floating point num), you can use this regex:

/^[-+]?[0-9]*\.?[0-9]+$/

And i suggest you to read some docs: https://www.regular-expressions.info/floatingpoint.html

I suppose you need to use a string instead of float type right? If you can use a numeric format in your database, you can use: http://guides.rubyonrails.org/active_record_validations.html#numericality

Patrick Barattin
  • 617
  • 6
  • 18