tags:

views:

86

answers:

3

Hello All,

I want to validate the field whose datatype is float in the database.Please tell me the required expression and regular expression for the float datatype so that user can enter only the digits in float.

for example this is giving error

else if(!Regex.IsMatch(lowerlimit, 
        @"[+-]?(?:(?:\d+\.\d*)|(?:\d*\.\d+))"))
{
    ModelState.AddModelError("lowerlimit", "Please enter valid lower limit");
}

Thanks Ritz

A: 

Try something like this:

^\d*\.?\d*$

Andrew Hare
wouldn't this match `.` or an empty string?
Amarghosh
Indeed it would.
ApoY2k
+1  A: 
[+\-]?(?:(?:\d+(\.\d*)?)|(?:\d*\.\d+))

You can drop the non-capturing ?: tags if you want to make it more readable.

[+\-]?((\d+(\.\d+)?)|(\d*\.\d+))

Note: this regex will match only floating point numbers with a decimal point - not integers.

Amarghosh
Updated so that it won't match things like `12.` Thanks to Douglas's regex.
Amarghosh
A: 

1st: It looks like you've fallen in the common trap: You had one problem, you decided to solve it with regular expressions, and now you have two problems.
You should see if you can use your standard library to try and parse the prospective float into a float, to avoid having to mess around with approximate regular expressions.

Depends what styles of floating point number text representation you want to allow.

Scientific notation:

[-+]?\d(\.\d+)?([eE]-?\d+)?

Simple decimal point:

-?\d+(\.\d+)?

Allow empty integer part:

[-+]?((\d*\.\d+)|(\d+(\.\d+)?))
Douglas Leeder
`.4` is a valid float number, right?
Amarghosh
@Amarghosh: yes, in many programming languages, the literal `.4` is valid. I guess it all depends on what type of values Ritz considers valid.
Bart Kiers