Asp.net MVC 5 model validation regex not validating special characters - asp.net

I have using ASP.NET MVC 5 and for validation I am using the regular Jquery unobtrusive validation library.
Currently I am facing an issue, The regular expression validation is working all right on client side but on server side its not validating the value.
[RegularExpression(#"^[0-9]{19}$", ErrorMessage = "Invalid Value")]
public string Value{ get; set; }
this is the simple regular expression to validate 19 digits. Its working fine on client side it'll now allow ' or - or any thing to pass on but if i submit directly to server than the model is not being validated.
Do I need to do some thing special?

ModelBinding ( the process of mapping post/get values to a complex model) occurs when you send data via post/get/put/delete requests, if you are manually creating a class with validation classes somewhere those data/validation annotations won't apply.
you can validate models manually - Validate list of models programmatically in ASP.NET MVC
That said, there is a library called PostSharp that can enforce those rules even when you are creating custom object/models outside of MVC ( CodeContracts ) and if it doesn't validate it throws an exception. Keep in mind that this library is paid but it has free version available that might fit your needs.

Related

entity framework core exception handling db first

Background
With ef core code first approach, validation is robust and simple: https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/validation
With the database first approach, it seems like any validation is happening behind the scenes by the database when dbcontext.SaveChanges(); is called. What's worse, these exceptions are nebulous and entirely unhelpful, for example, SqlException: String or binary data would be truncated can be thrown if any of the string properties of any of the entities have too many chars (ours is a legacy app riddled with char(10) and such), or even if a key that is a string is left null.
Question
I want to know if there is any reasonable or accepted way of enforcing the validation. I've found this question which might help debugging, but I would like to enforce the constraints in code
Is there any better method than changing every auto property to one that throws if it's constraints aren't met?
EntityFramework Core does not enforce any validation at all. The validation rules you see in the example are enforced by MVC and not EF. One of the main reason for EF Core to remove validation check was that only. Validation are run in UI and then in EF and then again in database which is just redundant. Hence client side validation is left to the front-end (MVC in this case) and server side is done by database engine.
When you use database first approach, EF core does not generate any annotation for validation because it does not reason about them anyway. That means you would get only server side validation which means error during SaveChanges.
The only way to enforce constraint in the code (client side) is to write those annotations so that MVC can enforce them or write custom code to deal with it. The whole validation mechanism is transparent to EF.
I ended up going with a psuedo extension to the generator tooling. Since the DBContext is a partial class, I made a new class that has a main
public partial class DBContext{
public static void Main(string[]args){
DBContext context = new DBContext();
var modelbuilder = new Microsoft.EntityFrameworkCore.ModelBuilder(new Microsoft.EntityFrameworkCore.Metadata.Conventions.ConventionSet());
context.OnModelCreating(modelbuilder);
IMutableModel model=modelbuilder.Model;
from there I used Linq to transform the various info about each entity's properties and the annotations on them into List<KeyValuePair<string,List<KeyValuePair<Regex,string>>>> where the first pair's key is the entity name, and the value is a list of find and replace pairs to edit the code that had already been generated with the corresponding validation, one per property. Then all I had to do was abuse the fact that the tooling generates the classes in <className>.cs files, and iterate over my list, executing the replacements for each entity source code file.
I'd have preferred doing something a little less hacky, because I'm relying on format that the ef tooling outputs, but it works

ASP.Net Core and model validation

Suppose I have a model which I need to validate. I can add some validate attributes to the properties I want to validate. And it works pretty fine. But at some point I want to validate this model depending on other models (I will need t query db). And here there are some options.
create a special validate attribute which will lack dependency injection
delegate this validation to some business layer (manager) and in controller
_
if (Model.IsValid) {
if(!await Manager.Create(myModel)) {
Model.CopyErrors(Manager.Errors); // Extension method for Model
}
}
So what is the correct way of handling such a situation?
P.S. I am using asp.net core and entity framework core
What you need is Fluent Validation

ASP.Net , data validation should be in the controller, not the model, contrary to this tutorial example?

I am following ASP.NET MVC Music Store Tutorial by Jon Galloway Microsoft from http://mvcmusicstore.codeplex.com
While setting up this fictitious music store , we have Album.cs as the model with these lines of code
public class Album
{
[Required(ErrorMessage = "An Album Title is required")]
[StringLength(160)]
public string Title { get; set; }
//.......More code follows
What I find confusing is, why is the validation being done here by the Required attribute in the model, instead of the controller? Isn't the controller supposed to do the validation? or is that standard practice to do the validation in the model...suppposedly the tutorial is from microsoft?
Thank you
What I find confusing is, why is the validation being done here by the
Required attribute in the model, instead of the controller
Actually that's the domain model and it should have domain validation on it in order to ensure that it will stay consistent. On the other hand you should have a view model being exposed to the views on which perform view specific validation. And if this domain model will never be reused outside of this application you could rely only on the view model validation.
For example you will see many wrong examples putting view specific data annotation attributes on the domain models such as [DisplayFormat] and [Display]. All those examples are an illustration of bad design in which the domain models are used as view models.
You are using DataAnnotations in the Model that states that the Title field must be filled in before being posted back to the server. In the controller you can also check if ModelState.IsValid however adding the DataAnnotations at the Model level is the correct way to implement data validation.
we generally use Microsoft enterprise library's validation block to validate in the controller. Which enable us to add or remove validations
easily by modifying config file.

Formatting uri template string values in ASP.NET WebApi

I have an ASP.NET WebApi application that has some controller methods that expect certain strings to be passed in as method parameters (declared as part of the route template).
On all the methods, the strings passed in are base64-encoded -- which means each controller method must base64-decode them before doing anything with them. While I can obviously have each method do this easily enough, I was wondering if there was a way to perform the decoding before the string actually gets passed to the controller method. I presume this is something along the lines of an action filter or custom formatter, but I'm not familiar enough with asp.net web api to know where to start on that?
Summary:
I've got route templates like : {controller}/{encodedString}/whatever
where {encodedString} is always a base64-encoded string.
and controllers with methods like
GetWhatever(string encodedString)
{
Base64Decode(encodedString);
// do other stuff...
}
I would like to use some part of the asp.net webapi pipeline to decode {encodedString} before the controller method is actually called. What path should I start down in order to do this?
You can create a custom model binder and attach it to the parameters using the ModelBinderAttribute. In the model binder you then do the base64 decoding.
For a reference on parameter binding in Web API check:
How WebAPI does Parameter Binding

How to Integrate Enterprise Library Validation Application Block ValidationResults between WCF and ASP.NET?

Enterprise Library Validation Application Block (VAB) integrates with ASP.NET and also with WCF.
Is there a way to integrate ValidationResults created in WCF with ASP.NET?
e.g. an ASP.NET web page invokes a WCF service. The WCF service validates the data using VAB and returns validation information via a FaultContract. The ASP.NET page can take the results and display some error messages. However, a common approach is to indicate which fields have errors (e.g. inline message or asterisk). It seems that most of these approaches will involve being able to correlate the validation result with a control or with a validator.
I don't think there is an out of the box solution but was also curious if anyone had done this and what their approach was.
Since there is no out of the box solution and there aren't any answers posted, I will share what I implemented. I'm not in love with the approach but it is working for me.
Overview
The basic approach is for the ASP.NET page to populate a mapping between properties on the DataContract objects to the ClientId of the control that is being validated. When a validation error occurs the ClientId is returned back from the service to the asp.net page as part of a FaultContract. Then the details from the FaultException are extracted; the ASP.NET page retrieves the ClientId of the control that caused the error and appropriate action can be taken (e.g. change control look and feel or set the text on a validator).
Details
All of the DataContract objects inherit from a base class that exposes a Dictionary. This dictionary is used to map object properties to ASP.NET controls. In the Dictionary, the key is the property name on the DataContract object and the value is the ClientId of the control. Before invoking a service, the client must attach the Dictionary to the DataContract object.
When a ValidationResult is created by Enterprise Library it contains a property called Target which is the object that was validated. ValidationResult also contains a property called key which is the name of the property from the target object that was validated. The ValidationResult key is also a key into the Dictionary that was set in the ASP.NET page before calling the service.
With the ValidationResult key, the ASP.NET supplied information (ClientId) can be extracted from the ValidationResult Target. The information is then added as the Tag of the ValidationResult. Unfortunately, Tag is a readonly property so it has to be set by creating a new ValidationResult and passing the tag to the constructor.
The collection of ValidationResults is then transformed to a pre-existing CustomValidationResults collection (which looks just like ValidationResult) that we needed to use. The CustomValidationResults are then added to a custom ValidationFault and a FaultException is thrown.
The ValidationFaults are then extracted from the FaultException in the ASP.NET page. The ValidationFault contains the ClientId of the control which is associated with the error so the page can choose to display the Messages as it sees fit.

Resources