JonathanWolfson
JonathanWolfson

Reputation: 861

Bifurcating Validation Error Messages in .Net

In ASP.Net, how do I limit validation messages to only one?

Rule: User must put in a number between 0 and 1000.

Current [undesired] Behavior:

User types 1001: validator says "Please put in a non-negative number beneath 1000"
User types -1: validator says "Please put in a non-negative number beneath 1000"

Desired Behavior:

User types 1001: validator says "Please put in a number beneath 1000"
User types -1: validator says "Please put in a non-negative number"

In other words, how can I use two asp:RangeValidators whose disallowed values intersect but only turn on the desired one? I do not want to handle a ServerValidate event on the server.

Is it doable without client-side code?

Upvotes: 0

Views: 231

Answers (3)

Jeff Sternal
Jeff Sternal

Reputation: 48623

You can use a CompareValidator to checks whether the value is less than zero and a RangeValidator to check whether the value is between -2147483647 and 1000.

<asp:CompareValidator Id="IsNotNegativeValidator"
                      ControlToValidate="TextBox1"
                      ValueToCompare="-1"
                      Operator="GreaterThan"
                      Type="Integer"
                      Text="Please put in a non-negative number"
                      runat="server"/>

<asp:RangeValidator   Id="IsLessThanOneThousandValidator"
                      ControlToValidate="TextBox1"
                      MinimumValue="-2147483647"
                      MaximumValue="1000"
                      Type="Integer"
                      Text="Please put in a number beneath 1000"
                      runat="server"/>

(In this particular case, it does seem like a single RangeValidator with the message "Please enter a number between 0 and 1000" would result in less user frustration.)

Upvotes: 1

Jamie Ide
Jamie Ide

Reputation: 49291

The best way I've found to do this is to use the RegularExpressionValidator exclusively. You can validate anything with the appropriate regular expression.

Upvotes: 0

AakashM
AakashM

Reputation: 63358

Your 'desired' behaviour has the potential to be somewhat irritating:

  • User enters 1001
  • App tells user "Please put in a number beneath 1000"
  • Fair enough, user thinks, and enters -1 (which you will agree is "a number beneath 1000")
  • App then tells user "Please put in a non-negative number"
  • Why didn't you mention that to start with!?, user thinks to themselves

What I'm asking is: What's wrong with the existing behaviour, whereby the user is told the actual rule?

Upvotes: 1

Related Questions