0

I need to write use a custom validator to check to see if a textbox has a number with a decimal for instance 95.3 in it. What is the expression to accomplish in validator server controls in asp.net?

Will
  • 1,084
  • 5
  • 20
  • 42
  • Do you want to fail validation if the user's input contains a decimal or require it to have a decimal? – lukiffer Nov 28 '11 at 17:46

4 Answers4

0

Not sure if this is exactly what you're looking for, but there's this post I've seen a long time ago which kinda explains how to do it. You might wanna take a look: http://aspdotnet-sequel.blogspot.com/2009/05/aspnet-textbox-validate-integer-float.html

MilkyWayJoe
  • 9,082
  • 2
  • 38
  • 53
0

Something like this should work, you can modifiy to allow as many decimal places you need or want:

\d{0,}.\d{0,2}

Assuming you are speaking about regular expressions. But if you were you should use a regular expression validator instead of a custom one.

Also, here is a link to another question that is very similar. link

Community
  • 1
  • 1
Etch
  • 3,044
  • 25
  • 31
0

In the validator_ServerValidate event you can do this:

Protected Sub CustomValidator1_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles CustomValidator1.ServerValidate
    If args.Value.Contains(".") Then
        '*** Textbox has a decimal...do what you need to handle it  ***'

    End If
End Sub

But as others mention, without knowing a bit more about what exactly you need to have happen, you would probably want to look at either a Regular Expression validator and try to validate on the client-side instead of server-side (unless you need to have it happen on the postback)

Chris
  • 459
  • 2
  • 3
  • While this in fact will detect whether certain string contains a dot "." or not, it will also find a dot on any other string. – Hanlet Escaño Nov 28 '11 at 18:03
  • As I mentioned he needs to be more descriptive about how he wants the validation to occur...if it needs to be server side, then he can also simply check to see if the value is numeric as well (hopefully he knows how to do that at least). – Chris Nov 28 '11 at 18:06
0

Please try the following:

float f;
bool isFloat =float.TryParse("a.0", out f); //Will return false

bool isFloat2 =float.TryParse("95.3", out f); //will return true

Good luck!

Hanlet Escaño
  • 17,114
  • 8
  • 52
  • 75