开发者

Bifurcating Validation Error Messages in .Net

开发者 https://www.devze.com 2022-12-17 12:11 出处:网络
In ASP.Net, how do I limit validation messages to only one? Rule: User must put in a number between 0 and 1000.

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?


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.)


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?


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

0

精彩评论

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