Validating view data before its set into the model - validation

My model object superficially is quite simple I don't think its worth describing my model, but a good analogy would be a SQL connection string, its just a string, but the rules for constructing it are quite complex, requiring a number of conditional UI elements depending on the DB, and other options.
Some of the data I have in the view can not be written to back to the Model if its invalid (imagine the database name is a quoted string, if a quote character is entered by the user, this can’t be written into the connection string without making the connection string unreadable).
The blazor validation API requires a model object to work from, so how do I create a validator for my blazor control that reports the errors against the invalid view fields. In this case the model is just the ConnectionString string field, and although I could write a custom validator for that, the data in it may not represent the data in the view, as the view can't always be written to the model.
UPDATED With Code
The following code shows the concept, I can't find a way for the validation rules in ConnectionStringViewModel to be run within the DatabaseInfoEditor.
class DatabaseInfoModel
{
[MaxLength(10)]
public string Name {get;set;}
[ValidateComplexType] // used to cause validation of child objects - but there is no child object to validate, what we want to validate is the ConnectionStringViewModel
public string ConnectionString {get;set;}
}
DatabaseInfoEditor.razor
<EditForm Model="MyDatabaseInfoModel">
<ObjectGraphDataAnnotationsValidator />
Name:<TextEditor #bind-Text="MyDatabaseInfoModel.Name"/>
<ConnectionStringEditor ConnectionString="MyDatabaseInfoModel.ConnectionString "/>
</EditForm>
ConnectionStringEditor.razor
Database:<TextEditor #bind-Text="MyConnectionStringViewModel.Database"/>
Username:<TextEditor #bind-Text="MyConnectionStringViewModel.Username"/>
#code
{
[Parameter]
public string ConnectionString {get;set;}
ConnectionStringViewModel MyConnectionStringViewModel;
override OnParameterSet()
{
base.OnParameterSet();
MyConnectionStringViewModel = PickApartConnectionString(ConnectionString);
}
class ConnectionStringViewModel
{
[MaxLength(10)]
public string Database {get;set;}
[MaxLength(10)]
public string Username {get;set;}
}
}

Related

WebAPI OData v4 - Using a class to represent an action's parameters

I want to add an action to my OData controller. I'll be calling this action with the request body matching the following structure, and with the following validation requirements:
public class PublishModel
{
[Required, EnumDataType(typeof(JobEventType))]
public JobEventType Type { get; set; }
[Required, StringLength(100)]
public string ExternalRef { get; set; }
public DateTimeOffset? DateTime { get; set; }
}
With a normal ApiController, I'd normally have my controller method simply take an argument of this type, and it'd work. With OData, it seems I have to implement my method using a ODataActionParameters argument.
I can't figure out how I'm supposed to tell OData that the body of the request should match the above. The closest I've got is to have it expect it in a parameter:
var pa = mb.EntityType<Edm.JobEvent>().Collection.Action("publish");
pa.ReturnsFromEntitySet<Edm.JobEvent>("jobevent");
pa.Parameter<PublishModel>("evt");
But this requires me to send
{"evt":{"type":"...","externalRef":"...","dateTime":"..."}}
When what I want to send is just
{"type":"...","externalRef":"...","dateTime":"..."}
I understand that I can just specify the properties of my class as individual parameters, but that'll be harder to maintain and I'll lose the data annotation validation. Is there a way to handle this?

How to make fields on ViewModel required for Web API call?

I want to know if it is possible or how can I mark fields on my class used as a parameter on my Web API call to be required? I obviously can do this manually once I have received the message, but I was hoping there was something built in the pipeline (like in MVC in combination with jQuery that uses required field annotations to automatically kick back to UI showing required field notations) so I don't have to check everything manually.
Let's say I have the following ViewModel class:
public class PersonViewModel
{
public string FirstName {get; set;}
public string MiddleName {get; set;}
public string LastName {get; set;}
}
Here is my simple Post method on a PersonController
public HttpResponseMessage Post(PersonViewModel person)
{
}
Let's say the FirstName and LastName fields are required but not MiddleName. What I want to know is will the call automatically respond back to the client with a HTTP 400 Bad Request or similar if the Person object does not have one of the required fields populated?
Essentially do I have to do all of this work manually, or is there a way to have the framework handle notated fields automatically, so I don't have a lot of boilerplate validation code for required fields?
Manual Way I'm trying to avoid:
if (ModelState.IsValid)
{
if (person.LastName == string.empty)
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
}
Any help is appreciated, thanks!
WebAPI does have a validation feature. You should be able to mark the FirstName and LastName properties as [Required] and then use the action filter at the bottom of this blog post to send back an appropriate response:
http://blogs.msdn.com/b/youssefm/archive/2012/06/28/error-handling-in-asp-net-webapi.aspx
You can read more about WebAPI validation here:
http://www.asp.net/web-api/overview/formats-and-model-binding/model-validation-in-aspnet-web-api

Web API parameters binding

I have this action in Web Api controller:
public Data GetData(ComplexModel model)
and model is
class ComplexModel
{
Guid Guid1 { get; set;}
Guid Guid2 { get; set;}
string String1 { get; set;}
}
i would like to specify custom binder for Guid type such as empty string or null would bind to empty guid and would like not use nullable type. Was trying to register model binder like this:
var pb = configuration.ParameterBindingRules;
pb.Insert(0, typeof(Guid), param => param.BindWithModelBinding(new GuidBinder()));
but it is not called and I am getting invalid model state with error message that empty string cant be converted to type Guid.
Remember, ParameterBindingRules checks the controller action parameter itself (ComplexModel in your case), not the contents of the parameter. You'd need to register a parameter binding against ComplexModel and do any processing with the custom binder to validate the model instance. Seems like you're better off making the Guid properties nullable despite your reluctance to do so.

Validating and modifying a variable from MetaData Class

I’m using ASP.NET MVC 3 for a project I have.
The problem is that I would like to save a value to the database, which should before saving into the database be "cleaned" (say removing trailing and ending spaces, and also validate).
I use a MetaData Class to validate the models before I save it to the database with data annotations, using the following code to validate:
if (ModelState.IsValid) {
My MetaData Class looks like this:
public class OrganizationMD {
[Required(ErrorMessage = "*This field is required.")]
[CustomValidationRule(ErrorMessage = "*Another error message")]
public string OrganizationNumber;
}
My first idea was to give the OrganizationNumber string a getter and setter, and there let the value become “fixed”.
For example if someone tries to save a company with "19860415-4785" as organizationnumber, it should automatically remove the trailing "19" and the dash in the string before validating and saving that new value into the database.
I can’t give the model a getter and setter because we’re developing using Model-First, otherwise I think that should work.
Does anyone have any idea how to solve this?
You could create a view model to pass the the data to/from the view and controller instead of using your domain (entity framework) model directly.
Put your data annotations on the view model's property.
public class OrganizationMDViewModel
{
[Required(ErrorMessage = "*This field is required.")]
[CustomValidationRule(ErrorMessage = "*Another error message")]
public string OrganizationNumber {get; set;}
}
Then you can do whatever you think will work in the getter and setter before mapping back to the domain model for persisting.
For readability and easier debugging, you could do your 'cleaning' in the controller instead of in the getter and setter, but that's up to you.
[HttpPost]
public ActionResult SaveData (OrganizationMDViewModel viewModel)
{
if (ModelState.IsValid) {
viewModel.OrganizationNumber...//clean up the value here
OrganizationMD = new OrganizationMD{OrganizationNumber = viewModel.OrganizationNumber}
//...and save
}
}

mvc3 validation when using buddy classes

I am working on an mvc3 application and having some problems with getting validation to work as I want.
The application is using buddy classes for the models. (This is something I haven't used in the past and I am a little confused why they are used...anyway)
I want to add required fields to ensure data been submitted is correct. I have tried adding the required field to the buddy class.
When I submit the form no client-side validation takes place and the debugger steps into the entity frameworks generated code. Here is complains that the fields that contain null values are causing are invalid. If I step through all of those it finally gets to the controller where my if (ModelState.IsValid) is showing false.
I have client-side validation switched on.
Am I meant to be applying the data validation at the buddy class level or at the view model?
One other question is why use buddy classes? to me they seem to over complicate things.
Updated added an example of the buddy class
[MetadataType(typeof (CustomerMetaData))]
public partial class Customer
{
public string Priorty
{
get
{
var desc = (Priority) Priority;
return desc.ToString().Replace('_', ' ');
}
}
internal class CustomerMetaData
{
[Required]
[DisplayName("Priorty")]
public string Priorty { get; set; }
Buddy classes are metadata classes to put data annotation attributes when you are not in control of the original class i.e. can't edit it. Typical situation is when the class is generated by an ORM like Entity Framework.
//Can't edit this class
public partial class YourClass{
public string SomeField {get; set;}
}
//Add a partial class
[MetadataType(typeof(YourClassMetadata))]
public partial class YourClass{
}
//And a metadata class
public class YourClassMetadata
{
[Required(ErrorMessage = "Some Field is required")]
public string SomeField {get; set;}
}
are you sure that you have [MetadataType(typeof(YourClassMetadata))]?
More about buddy classes here and here
You would typically use a buddy class when it isn't possible to add meta data to an entity class such as when a model is automatically generated by an ORM tool. In this case any meta data you had applied would be lost.
Therefore, your original (automatically generated) class would be defined as a partial class:
public partial class Customer
{
public string Priority { get; set; }
}
And then you would generate your buddy classes to add the meta data.
[MetadataType(typeof(CustomerMetaData))]
public partial class Customer
{
}
internal class CustomerMetaData
{
[Required]
public string Priority { get; set; }
}
You would then pass the Customer class to the view where the Priority would be set.
In your case i'm not sure if you only have one partial class or two (as the other is not shown but please provide if there is). I'm interested to know how you obtain the priority information from the customer as i'm wondering if this is an issue with how you use ModelState.IsValid? The reason I ask is that no set accessor is declared on the Priority property so i'm wondering how this is set from the view in order to report that it is not valid?
You would also use a buddy class when it isn't possible to add meta data to an entity class such as when a model is automatically generated by an WCF Data Contract.

Resources