Friendly Way to Handle Potentially Dangerous Values - asp.net-mvc

I'm after a friendly way to handle A potentially dangerous Request.Form value was detected
I want to be able to validate it myself and return my own validation message.
I was thinking of using the [AllowHtml] attribute then checking to see if the value contains potentially dangerous content via another ValidateAttribute or using IValidatableObject.
Is there a built in helper to manually validate the property's value?
Is there a better way of doing what I'm trying to achive?

Why not use [AllowHtml] together with another validation like that:
[AllowHtml]
[RegularExpression("(\<[a-zA-Z\!\/\?]|&#|script\s*\:)", ErrorMessage = "Invalid characters or whatever your message is")]
public string Description { get; set; }
See Security Extensibility in MVC4 document for more info. Hope it helps!

Related

Umbraco 7 MVC - Request.Form gives me dangerous request error

In the shopping basket of my site, i need to allow a form POST of XML coming from a third-party service.
The possible solutions i can find is for webforms and < Umbraco 7.
I'm aware that you can disable page validation entirely, but that's not an option in my case.
Does someone know the equivalent way of using the control <umbraco:DisableRequestValidation runat="server"/> in MVC?
for security reason, I would suggest try use [AllowHtml] on property which would contain the xml content
so say you viewmodel has property call ThirdPartyContent which will have xml:
public class VM
{
public string Name { get; set; }
[AllowHtml]
public string ThirdPartyContent { get; set; }
}
this implicit state which property you are aware will contain potential malicious content (which is angle bracket)
[ValidateInput(false)] does the trick but will assume all property may contain xml content which may not be good thing
more info checkout this SO answer which say the difference between [AllowHtml] and [ValidateInput(false)]
ValidateInput(false) vs AllowHtml
I found the answer to my own question.
It's possible to set the [ValidateInput(false)] annotation on RenderMvcControllers. So you can do it per document type which is kinda nice.
I'll leave the answer here in case someone else needs to do the same thing.

How to validate that user enters string in textbox in asp mvc4

How to validate that user enters string in textbox in asp mvc4?
What to write in required tag?
[required]
Use the [RegularExpression] attribute if you want to limit the user to only typing in alphabetic characters.
More info on MSDN.
Here is a good link to a regular expression that you can use.
This example maybe helps:
public class CustomerMetaData
{
// Require that the Title is not null.
// Use custom validation error.
[Required(ErrorMessage = "Title is required.")]
public object Title;
// Require that the MiddleName is not null.
// Use standard validation error.
[Required()]
public object MiddleName;
}
There are many ways to do it
1) By using plain Javascript or JQuery to check if it has value before submiting the page
2) On controller method check if it has value
3) If you a using EF and your view binded to a model add attribute called [Required]to the property of that model.
What do you actually want to do?
Make sure that the object the server receives has correct data in it? Then you should use data attributes on your C# model. However what do you mean by "enters string"? If the user simply needs to enter any string, then [Required] works - this just means that there has to be some value entered. Do you only want to allow a specific set of characters, like the English alphabet? Then you need to use a RegularExpression attribute.
If you further specify what you actually want to do I am sure we can help you more.

How can I validate an email address using the same method used by the DataAnnotations attribute DataType.EmailAddress?

I am using MVC3 and in certain locations in the code I am using the System.ComponentModel.DataAnnotations.DataType.EmailAddress attribute and letting MVCs Model validation do the validation for me.
However, I would now like to validate an email address in a different section of code where I am not using a model. I would like to use the same method that is already being used by MVC, however I was unable to find any information on how to do so.
EDIT - Sorry if my question was unclear. I will attempt to clarify.
Here is a snippet from the RegisterModel that is included with the default MVC template:
public class RegisterModel
{
...
[Required]
[DataType(DataType.EmailAddress)]
[DisplayName("Email address")]
public string Email { get; set; }
...
}
These attributes instruct mvcs model validation on how to validate this model.
However, I have a string that should contain an email address. I would like to validate the email address the same way that mvc is doing it.
string email = "noone#nowhere.com";
bool isValid = SomeMethodForValidatingTheEmailAddressTheSameWayMVCDoes(email);
As others have said, the DataType attribute doesn't actually do any validation. I would recommend you to look at Data Annotations Extensions which includes already written validation extensions for a variety of things, including Email.
It is also possible to do model validation on your full model explicitly: Manual Validation with Data Annotations.
If you want to do per attribute validation for a specific field/property, you can also look at the tests for DataAnnotationExtensions which should give you what you want:
[TestMethod]
public void IsValidTests()
{
var attribute = new EmailAttribute();
Assert.IsTrue(attribute.IsValid(null)); // Don't check for required
Assert.IsTrue(attribute.IsValid("foo#bar.com"));
..
}
Have a look at this blog post by Scott Guthrie, which shows how to implement validation of an email address using a custom attribute (based on the RegularExpressionAttribute).
You can reuse that logic if you need to validate the email address somewhere else.
You may want to look at this question: Is the DataTypeAttribute validation working in MVC2?
To summarize, [DataType(DataType.EmailAddress)] doesn't actually validate anything, it just says "hey, this property is supposed to be an e-mail address". Methods like Html.DisplayFor() will check for this and render it as foo, but the IsValid() method is pretty much a simple return true;.
You'll have to roll your own code to actually perform validation. The question linked above has some sample code you can use as a starting point.

change validate message in data annotation

my object has field with data type int. when i put in html form in this textbox letter not number the validator say- The field must be a number. how can i change this messages like this
[Required(ErrorMessage = "Введите название")]
[DisplayName("Название")]
public int age { get; set; }
I haven't found a clean way to achieve this using Data Annotations. One way would be to write a custom model binder but this seems like a lot of work to do for such a simple task.
Another way to achieve this is to add an App_GlobalResources folder to your ASP.NET application. Add a resource file called Messages.resx containing a PropertyValueRequired string resource.
PropertyValueRequired = "Some custom error message"
In your Application_Start register the resource class key:
protected void Application_Start()
{
RegisterRoutes(RouteTable.Routes);
DefaultModelBinder.ResourceClassKey = "Messages";
}
Note that ASP.NET MVC 2 uses the PropertyValueInvalid instead of PropertyValueRequired resource key.
IMO using Data Annotations to perform validation logic is limited (maybe in .NET 4 this will change). If you want to have full control over the validation logic I would recommend you using a validation library such as Fluent Validation or xVal.
I ran into the same problem and worked around it by specifying a RegularExpression that only allows positive natural numbers.
[Required(ErrorMessage = "Введите название")]
[DisplayName("Название")]
[RegularExpression(#"^[0-9]+$", ErrorMessage = "Поле возраст не является числом")]
public int age { get; set; }
Not sure if there are any downfalls to this solution. It seems to work fine for me.
PS: If you don't want to allow leading zeroes use "^[1-9]+[0-9]*$".
In retrospect: I have to admit though it's a bit weird to add a regular expression to an integer.

Is there any way to stop DataAnnotation validation after the first failure?

In my ViewModels I use several DataAnnotations to validate the form data, there are usually 2-3 annotations per field.
For example a field for an email address might look like this:
[Required(ErrorMessage = "Please enter an email address.")]
[Email(ErrorMessage = "That is not a valid email address.")] // Custom
public string Email { get; set; }
Now if someone were to submit the form, both errors would show up in the validation summary. Is there any easy way to specify an order to run the validation annotations so that if the Required validation fails, the Email validation doesn't run?
If this isn't possible, how is this usually handled? Should I create custom validators for any field that has more than a single annotation? Would that be a proper way to use annotations, where a single one handles multiple types of validation?
(I'm also aware I could probably combine the Required annotation into the custom Email one, but this is just an example).
In this specific case I would probably take the same approach that the ASP.NET WebForms validators take - simply have the EmailAttribute validator return true if the value is null or empty.
Think about it:
If the e-mail address is required, then there will also be a [Required] validator and a null/empty e-mail address will generate a validation error anyway;
If the e-mail address is optional, a null/empty value should be considered valid.
No need to solve the complex problem of intercepting validators when you can just design the individual validators to play nice together!
Ordering validation: No.
In this case you could simply remove the Required attribute because "" or " " will fail the email address validation.
And yes, AFAIK creating a custom validation attribute that combines both of them is probably your best bet.
The problem here is that the ordering on the attributes is completely arbitrary and decided at compile time. You actually can enforce simple ordering depending on the kind of validation runner you're using. If you are using something like xVal and a validation runner like the one mentioned here, you can add an orderby clause like this to force a specific kind of attribute to sort to the top:
orderby attribute.GetType() == typeof(T) ? 0 : 1
Just make a strongly-typed validation runner method, where T is derived from the ValidationAttribute class.

Resources