开发者

Regex or equivalent to accept float number in a textbox - asp.net C#

Good afternoon,

I need help to solve the following problem:

I need to restrict a range of values to a 开发者_高级运维textbox. I have already the minimum and maximum value allowed in the textbox, but is missing me intermediate values.

An example:

From the minimum value -2,00 to maximum value 0,00 it accepts: -2,00 | -1,75 | -1,50 | -1,25 | -1,00 | -0,75 | -0,5 | -0,25 | 0,00

From the minimum value 0,00 to maximum value 1,00 it accepts: 0,00 | 0,25 | 0,50 | 0,75 | 1,00

and so on..

What will be the best way to do that?

Thank you.


^(-[12]|[01]),00|(-[01]|0),(50|[27]5)$

(Can't add comment ..) @Filipe Costa - I don't know about min max, I think this would just validate from left to right. There is a definite length of 4 characters if the ^$ anchors are set.

(Can't add another comment ..)
@Filipe Costa - It gets harder to do charcter based validation, the more columns. I would let the control do numeric validation each keypress.

Here is a -127 - 128 character based validation test case (in Perl) to show how hairy it gets the more columns you have.

use strict;
use warnings;

 my $rx_128 = qr/
 ^ (?:
       - [1-9] (?: (?<=1)\d(?:(?<=[01])\d?|(?<=2)[0-7]? ) | \d? ) 
     |     \d  (?: (?<=1)\d(?:(?<=[01])\d?|(?<=2)[0-8]? ) | \d? )
   )
  $ /x;

# Test range -127 to 128

 my $count = 0;
 for (-5000 .. 5000)
 {
    if ( /$rx_128/ )
    {
        print $_,"\n";
        $count++;
    }
} 
print "\nOK = $count\n";


You could use a CustomValidator and write your own validation method to check if the value is a multiple of 0.25. You can add this to the page:

<asp:CustomValidator 
    ID="NumericInputValidator" 
    ControlToValidate="NumericInput"
    Display="Dynamic"
    runat="server" 
    OnServerValidate="ValidateNumericInput" 
    ErrorMessage="The given input must be a numberic value and it must be a multiple of 0.25" />

And then add something like this to the code behind:

protected void ValidateNumericInput(object sender, ServerValidateEventArgs args)
{
    decimal value;
    IFormatProvider formatProvider = CultureInfo.CurrentCulture; // Change this to the desired culture settings.
    bool isNumber = decimal.TryParse(args.Value, NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign, formatProvider, out value);

    // The number must be a multiple of 0.25, so when multiplied by 4, it should be an integer.
    args.IsValid = isNumber && decimal.Truncate(value * 4) == value * 4;
}


You should use a CustomValidator and have it check the steps you want given the arguments for the validator. Similar to a RangeValidator but with some custom logic.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜