I'm following along with a tutorial about creating a mini-RTS in Unity, but I've hit something of a roadblock when it comes to the selection feature for assigning selection groups for multiple units.
The pertinent parts are below:
In the Update() method of my UnitsSelection class
//manage selection groups with alphanumeric keys
if (Input.anyKeyDown)
{
int alphaKey = Utils.GetAlphaKeyValue(Input.inputString);
if (alphaKey != -1)
{
if (Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl))
{
_CreateSelectionGroup(alphaKey);
}
else
{
_ReselectGroup(alphaKey);
}
}
}
And the GetAlphaKeyValue method from Utils:
public static int GetAlphaKeyValue(string inputString)
{
if (inputString == "0") return 0;
if (inputString == "1") return 1;
if (inputString == "2") return 2;
if (inputString == "3") return 3;
if (inputString == "4") return 4;
if (inputString == "5") return 5;
if (inputString == "6") return 6;
if (inputString == "7") return 7;
if (inputString == "8") return 8;
if (inputString == "9") return 9;
return -1;
}
This is the code that is used in the tutorial, but to my understanding there is no way that _CreateSelectionGroup() would ever be called.
I've seen the tutorial demonstrate this functionality working, but whenever I try to run it GetAlphaKeyValue turns the Left and Right control keys into a -1 value so the if statement that checks for them never runs.
Am I missing something here? How does Unity normally handle things like Ctrl+1?
If you use the inputString I would always rather check for Contains instead of an exact string match. However, I tried to use the inputString in the past and I found it too unpredictable for most usecases ^^
While holding control keys your Keyboard most likely simply won't generate any inputString.
Only ASCII characters are contained in the inputString.
But e.g. CTRL+1 will not generate the ASCII symbol 1 but rather a "non-printing character", a control symbol - or simply none at all.
You should probably rather use e.g.
public static bool GetAlphaKeyValue(out int alphaKey)
{
alphaKey = -1;
if (Input.GetKeyDown(KeyCode.Alpha0) alphaKey = 0;
else if (Input.GetKeyDown(KeyCode.Alpha1) alphaKey = 1;
else if (Input.GetKeyDown(KeyCode.Alpha2) alphaKey = 2;
else if (Input.GetKeyDown(KeyCode.Alpha3) alphaKey = 3;
else if (Input.GetKeyDown(KeyCode.Alpha4) alphaKey = 4;
else if (Input.GetKeyDown(KeyCode.Alpha5) alphaKey = 5;
else if (Input.GetKeyDown(KeyCode.Alpha6) alphaKey = 6;
else if (Input.GetKeyDown(KeyCode.Alpha7) alphaKey = 7;
else if (Input.GetKeyDown(KeyCode.Alpha8) alphaKey = 8;
else if (Input.GetKeyDown(KeyCode.Alpha9) alphaKey = 9;
return alphaKey >= 0;
}
And then use it like
//manage selection groups with alphanumeric keys
if(Utils.GetAlphaKeyValue(out var alphaKey)
{
if (Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl))
{
_CreateSelectionGroup(alphaKey);
}
else
{
_ReselectGroup(alphaKey);
}
}
As it turns out it may just be an issue with my keyboard. Different keyboards handle key presses in different ways. Mine just refuses to tell Unity that control + (some other key) are being pressed together. Changed the code to respond to Shift + (some other key) and it works fine.
Related
This question already has answers here:
C# compiler error: "not all code paths return a value"
(9 answers)
Closed 1 year ago.
I am trying to write a function that receives an array and check that the array size is an odd number and that all the numbers preceding the middle index are bigger than it and all that follows are smaller and if so return true. I wrote the function but it keeps giving me this error.
this is my code:
thanks in advance.
static bool Balance(int[] array)
{
int count = 0, middle;
bool check = true;
foreach (int item in array)
{
count++;
}
if (count % 2 == 0)
check = false;
else
{
middle = array.Length / 2;
for (int i = 0; i < array.Length; i++)
{
if (i < middle)
{
if (array[i] < array[middle])
{
check = false;
continue;
}
}
if(i > middle)
if(array[i] > array[middle])
{
check = false;
}
}
}
if (check == false)
return false;
if (check == true)
return true;
The problem is that the compiler isn't as smart as you might think.
It doesn't know that the two last if cases covers all cases.
Switch to:
if (check == false)
return false;
else
return true;
And it will work!
Or just simplify:
return check;
When you write a method with a return type specified, make sure your code returns a value.
static bool Balance(int[] array)
{
int count = 0, middle;
bool check = true;
foreach (int item in array)
{
count++;
}
if (count % 2 == 0)
check = false;
else
{
middle = array.Length / 2;
for (int i = 0; i < array.Length; i++)
{
if (i < middle)
{
if (array[i] < array[middle])
{
check = false;
continue;
}
}
if(i > middle)
if(array[i] > array[middle])
{
check = false;
}
}
}
return check; // since you are checking the value in two `if` blocks, it would raise the error because compiler doesn't see the else part where the code flow will certainly go. this is the cleanest way in your code to return the value.
}
That's because compiler doesn´t know logic about your code and every path of your code needs to return a value.
In your case your simply can return the value of variable "check" at the end of your function.
change the last if to else and remove (check == true)
or just add 1 more line of code to your function
return false;
The error is occurred because in the end of your code you are using only if condition, you haven't returned any value for else condition.
if (check == false)
return false;
if (check == true)
return true;
You should write it in this way,
if(check == false)
{
return false;
}else return true;
Or simply you can just return the "check" variable as you are ultimately just returning the true value of this variable,
return check;
In the beginning i will tell that I'm new with C# and Programming. Trying to learn as much as i can alone.
My first learning project is simple. Moving trough array 10x10 by using "W, S, A, D". It is "game" which is letting user to move his character trough array. The problem is that i want "my character" to move as long as his position will be out of range. So i think i'm trying to make infitive loop which is printing position and lets moving forward. If i'm using for example do{}while(true), position is changing all the time after pressing one key. I'm looking for suggestion how should i construct loop for this kind of "movement".
I'm attaching my code which is responsible for moving character.
int axisx = 0;
int axisy = 0;
var movement = Console.ReadKey();
int[,] level = new int[10, 10];
if (movement.Key.ToString() == "W"){axisy = axisy+1;}
else if (movement.Key.ToString() == "S"){axisy = axisy-1;}
else if (movement.Key.ToString() == "D"){axisx = axisx+1;}
else if (movement.Key.ToString() == "A"){axisx = axisx-1;}
Console.WriteLine("{2} is on position:{0},{1}", axisx, axisy, Player1.getBuilderName());
if (movement.Key == ConsoleKey.Escape)
{
Console.WriteLine("You pressed Escape, Goodbye");
}
You can use a while(true) loop:
int axisx = 0;
int axisy = 0;
while (true)
{
var movement = Console.ReadKey();
if (movement.KeyChar == 'W' || movement.KeyChar == 'w')
{
axisy += 1;
}
else if (movement.KeyChar == 'S' || movement.KeyChar == 's')
{
axisy -= 1;
}
else if (movement.KeyChar == 'D' || movement.KeyChar == 'd')
{
axisx += 1;
}
else if (movement.KeyChar == 'A' || movement.KeyChar == 'a')
{
axisx -= 1;
}
Console.WriteLine("{2} is on position:{0},{1}", axisx, axisy, Player1.getBuilderName());
if (movement.Key == ConsoleKey.Escape)
{
Console.WriteLine("You pressed Escape, Goodbye");
break;
}
}
The break; in the ConsoleKey.Escape block will get you out of the loop.
You can also use movement.KeyChar instead of movement.Key.ToString(), strings are immutable in .NET, so every time you do a ToString() you are creating a new string.
Note: Using .Net 4.0
Consider the following piece of code.
String ad = "FE23658978541236";
String ad2 = "00FABE002563447E".ToLower();
try
{
PhysicalAddress.Parse(ad);
}
catch (Exception)
{
//We dont get here, all went well
}
try
{
PhysicalAddress.Parse(ad2);
}
catch (Exception)
{
//we arrive here for what reason?
}
try
{
//Ok, I do it myself then.
ulong dad2 = ulong.Parse(ad2, System.Globalization.NumberStyles.HexNumber);
byte[] bad2 = BitConverter.GetBytes(dad2);
if (BitConverter.IsLittleEndian)
{
bad2 = bad2.Reverse().ToArray<byte>();
}
PhysicalAddress pa = new PhysicalAddress(bad2);
}
catch (Exception ex)
{
//We don't get here as all went well
}
So an exception is thrown in PhysicalAddress.Parse method when trying to parse an address with lower case. When I look at the source code of .Net its totally clear to me why.
Its because of the following piece of code.
if (value >= 0x30 && value <=0x39){
value -= 0x30;
}
else if (value >= 0x41 && value <= 0x46) {
value -= 0x37;
}
That is found within the Parse method.
public static PhysicalAddress Parse(string address) {
int validCount = 0;
bool hasDashes = false;
byte[] buffer = null;
if(address == null)
{
return PhysicalAddress.None;
}
//has dashes?
if (address.IndexOf('-') >= 0 ){
hasDashes = true;
buffer = new byte[(address.Length+1)/3];
}
else{
if(address.Length % 2 > 0){ //should be even
throw new FormatException(SR.GetString(SR.net_bad_mac_address));
}
buffer = new byte[address.Length/2];
}
int j = 0;
for (int i = 0; i < address.Length; i++ ) {
int value = (int)address[i];
if (value >= 0x30 && value <=0x39){
value -= 0x30;
}
else if (value >= 0x41 && value <= 0x46) {
value -= 0x37;
}
else if (value == (int)'-'){
if (validCount == 2) {
validCount = 0;
continue;
}
else{
throw new FormatException(SR.GetString(SR.net_bad_mac_address));
}
}
else{
throw new FormatException(SR.GetString(SR.net_bad_mac_address));
}
//we had too many characters after the last dash
if(hasDashes && validCount >= 2){
throw new FormatException(SR.GetString(SR.net_bad_mac_address));
}
if (validCount%2 == 0) {
buffer[j] = (byte) (value << 4);
}
else{
buffer[j++] |= (byte) value;
}
validCount++;
}
//we too few characters after the last dash
if(validCount < 2){
throw new FormatException(SR.GetString(SR.net_bad_mac_address));
}
return new PhysicalAddress(buffer);
}
Can this be considered a bug? Or is it so very wrong to use a lower cased hex values in a string? Or is there some convention I am unaware of.
Personally, I consider this programmer unfriendly.
From MSDN:
The address parameter must contain a string that can only consist of
numbers and upper-case letters as hexadecimal digits. Some examples of
string formats that are acceptable are as follows .... Note that an address that contains f0-e1-d2-c3-b4-a5 will fail to parse and throw an exception.
So you could simply do: PhysicalAddress.Parse(ad.ToUpper());
No, it's only a bug if it doesn't do something the documentation states that it does, or it does something the documentation states that it doesn't. The mere fact that it doesn't behave as you expect doesn't make it a bug. You could of course consider it a bad design decision (or, as you put it so eloquently, programmer-unfriendly) but that's not the same thing.
I tend to agree with you there since I like to follow the "be liberal in what you expect, consistent in what you deliver" philosophy and the code could probably be easily fixed with something like:
if (value >= 0x30 && value <=0x39) {
value -= 0x30;
}
else if (value >= 0x41 && value <= 0x46) {
value -= 0x37;
}
else if (value >= 0x61 && value <= 0x66) { // added
value -= 0x57; // added
} // added
else if ...
though, of course, you'd have to change the doco as well, and run vast numbers of tests to ensure you hadn't stuffed things up.
Regarding the doco, it can be found here and the important bit is repeated below (with my bold):
The address parameter must contain a string that can only consist of numbers and upper-case letters as hexadecimal digits. Some examples of string formats that are acceptable are as follows:
001122334455
00-11-22-33-44-55
F0-E1-D2-C3-B4-A5
Note that an address that contains f0-e1-d2-c3-b4-a5 will fail to parse and throw an exception.
Errm...Let's see...The bug my project is having is...Weird.
I'm making a Monster Training game,and when it enters on the battle mode,there is a bug that may happen,once you press the key to the left or the right of the controls,before you enter on the battle.
The bug is simple,for example,if you press A(Aka left button),when it lets you choose the action you will take,the game keeps recognizing as if the A button is still pressed,even if it isn't.
This is the code that is causing the bug:
public static int ChooseAction()
{
int choosen = 0;
Battle.CanAct = true;
Battle.ChoosenAction = -1;
while (Battle.ChoosenAction == -1)
{
if (Battle.KeyDelay == 0)
{
if (Procedures.ButtonPressed(Procedures.KeyCodes.KeyRight))
{
Battle.KeyDelay = 64;
int a = Battle.SelectedAction;
a++;
if (a >= BattleActions.Length)
{
a -= BattleActions.Length;
}
Battle.SelectedAction = a;
}
else if (Procedures.ButtonPressed(Procedures.KeyCodes.KeyLeft))
{
Battle.KeyDelay = 64;
int a = Battle.SelectedAction;
a--;
if (a < 0)
{
a += BattleActions.Length;
}
Battle.SelectedAction = a;
}
else if (Procedures.ButtonPressed(Procedures.KeyCodes.Action))
{
Battle.ChoosenAction = Battle.SelectedAction;
}
}
if (KeyDelay != 0 && !Procedures.ButtonPressed(Procedures.KeyCodes.KeyRight) && !Procedures.ButtonPressed(Procedures.KeyCodes.KeyLeft))
{
KeyDelay = 0;
}
if (Battle.KeyDelay > 0)
{
Battle.KeyDelay--;
}
}
choosen = Battle.ChoosenAction;
Battle.CanAct = false;
return choosen;
}
I don't know if this will help,but that script runs on a thread,since it's maden based on the modification of the official script,that were in c# console.
Also,the ButtonPress procedure,returns if the button is pressed,but it ever creates a new boolean everytime it is called.
Any clue of what may be causing the bug?
The Procedures.ButtonPress(KeyCodes) script.
public static bool ButtonPressed(KeyCodes buttonKey)
{
bool pressed = false;
switch (buttonKey)
{
case KeyCodes.MenuKey:
if (Keyboard.GetState().IsKeyDown(Microsoft.Xna.Framework.Input.Keys.M) || GamePad.GetState(PlayerIndex.One).IsButtonDown(Microsoft.Xna.Framework.Input.Buttons.Start))
pressed = true;
break;
case KeyCodes.RunKey:
if (Keyboard.GetState().IsKeyDown(Microsoft.Xna.Framework.Input.Keys.LeftShift) || Keyboard.GetState().IsKeyDown(Microsoft.Xna.Framework.Input.Keys.RightShift) || GamePad.GetState(PlayerIndex.One).IsButtonDown(Microsoft.Xna.Framework.Input.Buttons.B))
pressed = true;
break;
case KeyCodes.KeyUp:
if (Keyboard.GetState().IsKeyDown(Microsoft.Xna.Framework.Input.Keys.W) || Keyboard.GetState().IsKeyDown(Microsoft.Xna.Framework.Input.Keys.Up) || GamePad.GetState(PlayerIndex.One).IsButtonDown(Microsoft.Xna.Framework.Input.Buttons.DPadUp))
pressed = true;
break;
case KeyCodes.KeyDown:
if (Keyboard.GetState().IsKeyDown(Microsoft.Xna.Framework.Input.Keys.S) || Keyboard.GetState().IsKeyDown(Microsoft.Xna.Framework.Input.Keys.Down) || GamePad.GetState(PlayerIndex.One).IsButtonDown(Microsoft.Xna.Framework.Input.Buttons.DPadDown))
pressed = true;
break;
case KeyCodes.KeyLeft:
if (Keyboard.GetState().IsKeyDown(Microsoft.Xna.Framework.Input.Keys.A) || Keyboard.GetState().IsKeyDown(Microsoft.Xna.Framework.Input.Keys.Left) || GamePad.GetState(PlayerIndex.One).IsButtonDown(Microsoft.Xna.Framework.Input.Buttons.DPadLeft))
pressed = true;
break;
case KeyCodes.KeyRight:
if (Keyboard.GetState().IsKeyDown(Microsoft.Xna.Framework.Input.Keys.D) || Keyboard.GetState().IsKeyDown(Microsoft.Xna.Framework.Input.Keys.Right) || GamePad.GetState(PlayerIndex.One).IsButtonDown(Microsoft.Xna.Framework.Input.Buttons.DPadRight))
pressed = true;
break;
case KeyCodes.Action:
if (Keyboard.GetState().IsKeyDown(Microsoft.Xna.Framework.Input.Keys.Enter) || GamePad.GetState(PlayerIndex.One).IsButtonDown(Microsoft.Xna.Framework.Input.Buttons.A))
pressed = true;
break;
case KeyCodes.Return:
if (Keyboard.GetState().IsKeyDown(Microsoft.Xna.Framework.Input.Keys.Escape) || GamePad.GetState(PlayerIndex.One).IsButtonDown(Microsoft.Xna.Framework.Input.Buttons.B))
pressed = true;
break;
}
return pressed;
}
After downloading XNA and setting up everything (yes I'm bored at work), I tried the code on a simple menu and it works flawlessly.
The problem is that for some reason XNA's input is not threadable. It doesn't work at all for me when I create another thread with the input. I tried various keys and none of them get a pressed state but the letter "R" which once it's pressed, it stays that way.
I also tried with the R to save the original keyboard state and once the state changes use the original to compare if R was pressed and it worked. However, you will know just ONCE that R was pressed and you won't know if it's being pressed again.
After doing all that I googled and I found recommendations to ALWAYS check your input on your main thread on the update method (as I did at first)
Hope this helps =)
is anybody aware of a list of exactly what triggers ASP.NET's HttpRequestValidationException? [This is behind the common error: "A potentially dangerous Request.Form value was detected," etc.]
I've checked here, around the Web, and MSDN Library but can't find this documented. I'm aware of some ways to generate the error, but would like to have a complete list so I can guard against and selectively circumvent it (I know how to disable request validation for a page, but this isn't an option in this case).
Is it a case of "security through obscurity"?
Thanks.
[Note: Scripts won't load for me in IE8 (as described frequently in the Meta forum) so I won't be able to "Add comment."]
EDIT 1: Hi Oded, are you aware of a list that documents the conditions used to determine a "potentially malicious input string"? That's what I'm looking for.
EDIT 2: #Chris Pebble: Yeah, what you said. :)
I couldn't find a document outlining a conclusive list, but looking through Reflector and doing some analysis on use of HttpRequestValidationException, it looks like validation errors on the following can cause the request validation to fail:
A filename in one of the files POSTed to an upload.
The incoming request raw URL.
The value portion of the name/value pair from any of the incoming cookies.
The value portion of the name/value pair from any of the fields coming in through GET/POST.
The question, then, is "what qualifies one of these things as a dangerous input?" That seems to happen during an internal method System.Web.CrossSiteScriptingValidation.IsDangerousString(string, out int) which looks like it decides this way:
Look for < or & in the value. If it's not there, or if it's the last character in the value, then the value is OK.
If the & character is in a &# sequence (e.g., for a non-breaking space), it's a "dangerous string."
If the < character is part of <x (where "x" is any alphabetic character a-z), <!, </, or <?, it's a "dangerous string."
Failing all of that, the value is OK.
The System.Web.CrossSiteScriptingValidation type seems to have other methods in it for determining if things are dangerous URLs or valid JavaScript IDs, but those don't appear, at least through Reflector analysis, to result in throwing HttpRequestValidationExceptions.
Update:
Warning: Some parts of the code in the original answer (below) were removed and marked as OBSOLETE.
Latest source code in Microsoft site (has syntax highlighting):
http://referencesource.microsoft.com/#System.Web/CrossSiteScriptingValidation.cs
After checking the newest code you will probably agree that what Travis Illig explained are the only validations used now in 2018 (and seems to have no changes since 2014 when the source was released in GitHub). But the old code below may still be relevant if you use an older version of the framework.
Original Answer:
Using Reflector, I did some browsing. Here's the raw code. When I have time I will translate this into some meaningful rules:
The HttpRequestValidationException is thrown by only a single method in the System.Web namespace, so it's rather isolated. Here is the method:
private void ValidateString(string s, string valueName, string collectionName)
{
int matchIndex = 0;
if (CrossSiteScriptingValidation.IsDangerousString(s, out matchIndex))
{
string str = valueName + "=\"";
int startIndex = matchIndex - 10;
if (startIndex <= 0)
{
startIndex = 0;
}
else
{
str = str + "...";
}
int length = matchIndex + 20;
if (length >= s.Length)
{
length = s.Length;
str = str + s.Substring(startIndex, length - startIndex) + "\"";
}
else
{
str = str + s.Substring(startIndex, length - startIndex) + "...\"";
}
throw new HttpRequestValidationException(HttpRuntime.FormatResourceString("Dangerous_input_detected", collectionName, str));
}
}
That method above makes a call to the IsDangerousString method in the CrossSiteScriptingValidation class, which validates the string against a series of rules. It looks like the following:
internal static bool IsDangerousString(string s, out int matchIndex)
{
matchIndex = 0;
int startIndex = 0;
while (true)
{
int index = s.IndexOfAny(startingChars, startIndex);
if (index < 0)
{
return false;
}
if (index == (s.Length - 1))
{
return false;
}
matchIndex = index;
switch (s[index])
{
case 'E':
case 'e':
if (IsDangerousExpressionString(s, index))
{
return true;
}
break;
case 'O':
case 'o':
if (!IsDangerousOnString(s, index))
{
break;
}
return true;
case '&':
if (s[index + 1] != '#')
{
break;
}
return true;
case '<':
if (!IsAtoZ(s[index + 1]) && (s[index + 1] != '!'))
{
break;
}
return true;
case 'S':
case 's':
if (!IsDangerousScriptString(s, index))
{
break;
}
return true;
}
startIndex = index + 1;
}
}
That IsDangerousString method appears to be referencing a series of validation rules, which are outlined below:
private static bool IsDangerousExpressionString(string s, int index)
{
if ((index + 10) >= s.Length)
{
return false;
}
if ((s[index + 1] != 'x') && (s[index + 1] != 'X'))
{
return false;
}
return (string.Compare(s, index + 2, "pression(", 0, 9, true, CultureInfo.InvariantCulture) == 0);
}
-
private static bool IsDangerousOnString(string s, int index)
{
if ((s[index + 1] != 'n') && (s[index + 1] != 'N'))
{
return false;
}
if ((index > 0) && IsAtoZ(s[index - 1]))
{
return false;
}
int length = s.Length;
index += 2;
while ((index < length) && IsAtoZ(s[index]))
{
index++;
}
while ((index < length) && char.IsWhiteSpace(s[index]))
{
index++;
}
return ((index < length) && (s[index] == '='));
}
-
private static bool IsAtoZ(char c)
{
return (((c >= 'a') && (c <= 'z')) || ((c >= 'A') && (c <= 'Z')));
}
-
private static bool IsDangerousScriptString(string s, int index)
{
int length = s.Length;
if ((index + 6) >= length)
{
return false;
}
if ((((s[index + 1] != 'c') && (s[index + 1] != 'C')) || ((s[index + 2] != 'r') && (s[index + 2] != 'R'))) || ((((s[index + 3] != 'i') && (s[index + 3] != 'I')) || ((s[index + 4] != 'p') && (s[index + 4] != 'P'))) || ((s[index + 5] != 't') && (s[index + 5] != 'T'))))
{
return false;
}
index += 6;
while ((index < length) && char.IsWhiteSpace(s[index]))
{
index++;
}
return ((index < length) && (s[index] == ':'));
}
So there you have it. It's not pretty to decipher, but it's all there.
How about this script? Your code can not detect this script, right?
";}alert(1);function%20a(){//
Try this regular expresson pattern.
You may need to ecape the \ for javascript ex \\
var regExpPattern = '[eE][xX][pP][rR][eE][sS][sS][iI][oO][nN]\\(|\\b[oO][nN][a-zA-Z]*\\b\\s*=|&#|<[!/a-zA-Z]|[sS][cC][rR][iI][pP][tT]\\s*:';
var re = new RegExp("","gi");
re.compile(regExpPattern,"gi");
var outString = null;
outString = re.exec(text);
Following on from Travis' answer, the list of 'dangerous' character sequences can be simplified as follows;
&#
<A through to <Z (upper and lower case)
<!
</
<?
Based on this, in an ASP.Net MVC web app the following Regex validation attribute can be used on a model field to trigger client side validation before an HttpRequestValidationException is thrown when the form is submitted;
[RegularExpression(#"^(?![\s\S]*(&#|<[a-zA-Z!\/?]))[\s\S]*$", ErrorMessage = "This field does not support HTML or allow any of the following character sequences; "&#", "<A" through to "<Z" (upper and lower case), "<!", "</" or "<?".")]
Note that validation attribute error messages are HTML encoded when output by server side validation, but not when used in client side validation, so this one is already encoded as we only intend to see it with client side validation.
From MSDN:
'The exception that is thrown when a potentially malicious input string is received from the client as part of the request data. '
Many times this happens when JavaScript changes the values of a server side control in a way that causes the ViewState to not agree with the posted data.