MVC dynamic validation - asp.net-mvc

I get a requirement like this:
Different airlines require different traveller's information.
For example:
Airline A , need ID Number ,child birthday is required and age must between 2 ~ 12.
Airline B , need ID Number and gender.
Airline C, require all travellers' birthday, and child age must between 2 ~12.
etc...
My question is : Is there anyway in different scenarios use different validation rules ?
In addition , all children and adult's information collect in one page, so I need specify validation rule for instance of traveller.
How can I do it in MVC ?
Thanks.

Well you can use IValidateObject in mvc. you have not specified what you have done till now but i would have created an Airline viewmodel and validate it somewhat like this
public class AirlineViewModel: IValidatableObject
{
public string AirlineName{ get; set; }
public int IDNo{ get; set; }
// your other properties here
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
List<ValidationResult> err = new List<ValidationResult>();
if(AirlineName.Equals("Airline a"))
{
if(IDNo>0)
{
yield return new ValidationResult("ID cannot be empty", new[] { "IDNo" });
}
}
else if(AirlineName.Equals("Airline b"))
{
// your stuff here
}
else if(AirlineName.Equals("Airline C"))
{
// your stuff here
}
}
}

As mazhar mentioned, IValidateableObject is one option if you don't care about client-side validation. Another option creating your own data annotation attributes. A third option is to use a third party validation library like Fluent Validation.

Related

MVC 4 Localising Validation Messages from Database

Scenario :-
I am developing MVC 4 application, the website will run in several languages and will be hosted on Azure.
For localizing we are relying on the database rather than resource bundle approach.
Problem :-
I want to customize error messages at runtime, I want to localize the messages through the database.
I have tried to change attribute values through reflection but it had not worked.
Code :-
//Model
public class Home
{
[Required(ErrorMessage = "Hard coded error msg")]
public string LogoutLabel { get; set; }
}
//On controller
public ActionResult Index()
{
Home homeData = new Home();
foreach (PropertyInfo prop in homeData.GetType().GetProperties())
{
foreach (Attribute attribute in prop.GetCustomAttributes(false))
{
RequiredAttribute rerd = attribute as RequiredAttribute;
if (rerd != null)
{
rerd.ErrorMessage = "dynamic message";
}
}
}
return View(homeData);
}
On client side when validation takes place it shows me old message "Hard Coded error msg".
Please suggest how this can be customised if we donot want to use Resource bundle approach
You would better create and register your own DataAnnotationsModelMetadataProvider where you can just override the error messages. For more detail please see the answers to the similar question here MVC Validation Error Messages not hardcoded in Attributes
are you intended to implement this nested loop to localize validation message of all you'r entities ? i think no.a better solution is using Validator attribute.
for you'r class :
[Validator(typeof(HomeValidator))]
public class Home
{
public string LogoutLabel { get; set; }
}
now lets implement HomeValidator :
public class HomeValidator : AbstractValidator<Home>
{
public HomeValidator()
{
RuleFor(x => x.LogoutLabel ).NotEmpty().WithMessage("your localized message");
}
}

Is it possible to update ModelState.IsValid manually?

I would like to use the built-in validation features as far as possible. I would also like to use the same model for CRUD methods.
However, as a drop down list cannot be done using the standard pattern, I have to validate it manually. In the post back method, I would like to just validate the drop down list and add this result to ModelState so that I don't have to validate all the other parameters which are done with Data Annotation. Is it possible to achieve this?
I may be mistaken about the drop down list, but from what I read, the Html object name for a drop down list cannot be the same as the property in the Model in order for the selected value to be set correctly. Is it still possible to use Data Annotation with this workaround?
Thanks.
You can use the addModelError
ModelState.AddModelError(key,message)
when you use that, it will invalidate the ModelState so isValid will return false.
Update
after seeing the comment to #Pieter's answer
If you want to exclude an element from affecting the isValid() result, you can use the ModelState.Remove(field) method before calling isValid().
Another option is to inherit IValidatableObject in your model. Implement its Validate method and you can leave all other validation in place and write whatever code you want in this method. Note: you return an empty IEnumerable<ValidationResult> to indicate there were no errors.
public class Class1 : IValidatableObject
{
public int val1 { get; set; }
public int val2 { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var errors = new List<ValidationResult>();
if (val1 < 0)
{
errors.Add(new ValidationResult("val1 can't be negative", new List<string> { "val2" }));
}
if (val2 < 0)
{
errors.Add(new ValidationResult("val2 can't be negative", new List<string> { "val2" }));
}
return errors;
}
}
EDIT: After re-reading the question I don't think this applicable to this case, but I'm leaving the answer here in case it helps someone else.
You cannot manually set the ModelState.IsValid property but you can add messages to the ModelState that will ensure that the IsValid is false.
ModelState.AddModelError();
yes, you can achieve this (also you will use the same model for CRUD methods) :
Example MODEL
public class User
{
public virtual int Id{ get; set; }
public virtual Role Role { get; set; }
}
public class Role
{
[Required(ErrorMessage = "Id Required.")]
public virtual int Id { get; set; }
[Required(ErrorMessage = "Name Required.")]
public virtual string Name { get; set; }
}
Example VIEW with validation on the dropdownlist
#Html.DropDownListFor(m => m.Role.Id, (SelectList)ViewBag.gRoles, "-- Select --")
#Html.ValidationMessageFor(m => m.Role.Id)
CONTROLLER: clearing the required (but not needed here) fields
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Creedit(User x)
{
x.Role = db.RoseSet.Find(x.Role.Id);
if (x.Role != null)
{
ModelState["Role.Name"].Errors.Clear();
}
if (ModelState.IsValid)
{
// proceed
}
else
{
// return validation error
}
}
Might be more recent methods, since this is an old post, but this might help future readers.
One can set a field to valid with this two methods:
ModelState.ClearValidationState("Password");
ModelState.MarkFieldValid("Password");
Need to use both because the second one without the first one it gives an error stating that the state is already marked.
To set a field to invalid, just use ModelState.AddModelError() method as already referred.

asp.net mvc validation on 2 fields - one must exist if other entered

I have 2 text fields, text1 and text2, in my view model. I need to validate if text1 is entered then text2 must be entered and vice versa. How can this be achieved in the custom validation in the view model?
thanks.
You can use implement IValidatableObject (from System.ComponentModel.DataAnnotations namespace) for the server side validation on your View Model:
public class AClass : IValidatableObject
{
public int Id { get; set; }
public string Name { get; set; }
public string SecondName { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if( (!string.IsNullOrEmpty(Name) && string.IsNullOrEmpty(SecondName)) || (string.IsNullOrEmpty(Name) && !string.IsNullOrEmpty(SecondName)) )
yield return new ValidationResult("Name and Second Name should be either filled, or null",new[] {"Name","SecondName"});
}
}
Now it make sure if both Name and SecondName are set, or null, then model is valid, otherwise, it's not.
Look at mvc foolproof validation it does conditional validation. Find it on nuget or http://foolproof.codeplex.com
Edit
The above is really old
I'd recommend MVC Fluent Validation for anything modern https://docs.fluentvalidation.net/en/latest/aspnet.html
You can use JQuery, something like this:
$("input[x2]").hide();
$("input[x1]").keypress(function() {
var textValue = ("input[x1]").val();
if(textValue)
$("input[x2]").show();
})
If you'd like to use a data annotation validator and validation attributes on your model, you should take a look at this:
" attribute dependent on another field"

Dynamically set required fields

I'm curious how I can dynamically set a model's validation attributes. For instance, I often have Views where certain fields should be required when a user is in a certain role, but not required when a user is in another role. I would like both the server-side and client-side validation to be set accordingly.
Wouldn't something like this work for you for the server side?
public class RequiredForRoleAttribute : ValidationAttribute
{
public string Role { get; set; }
public override bool IsValid(object value)
{
return !Roles.IsUserInRole(Role) || (value != null && !string.IsNullOrEmpty((string)value));
}
}
And an example usage will be;
[RequiredForRoleAttribute(Role = "Admins", ErrorMessage = "Phone number is required for members of the admin role.")]
public string PhoneNumber { get; set; }
Now for the client side of things,
Your going to have to register it for remote validation as described at the following link; http://forums.asp.net/t/1559594.aspx/1
Hope you get it,
Chris

ASP.NET MVC - Partially updating model from view

I just wondered how people were approaching this situation. It's something that seems like a weak point in my usage of MVC with ORMs (NHibernate in this case)...
Say you have a fine-grained and complicated entity in your model. You will likely have an admin page to manage objects of this type. If the entity is complicated, it is unlikely that you will be modifying the whole entity in one form. You still need to pass the relevant properties to the view, and incorporate changes to those properties in the model when the view returns them.
What does anyone do in this situation?
Create a view model which is (or contains) a subset of the entities properties. Pass this to and from the view. In 'edit' action method in controller, get the object from repository, go though all the properies in the ViewModel and apply them to the Model object (model.a = viewmodel.a, modelb = viewmodel.b). This seems the obvious sensible route, but generates a lot of tedious plumbing code. Also this complicates validation a bit.
Something else?
I've looked briefly at automapper - but this doesn't seem to fit the bill exactly, maybe I'm wrong?
Thanks.
This sounds like the perfect scenario for automapper. You create a view model class which contains a subset of the fields or your real model, and you let AutoMapper take care extraccting values from the domain model object into your view model object. What issues are you having with this approach?
Consider this example:
Here is your domain model and your view model
public class Person
{
public string FirstName
{ get; set; }
public string LastName
{ get; set; }
public string HomeNumber
{ get; set; }
public string Address1
{ get; set; }
public string Address2
{ get; set; }
}
public class PersonViewModel
{
public string FirstName
{ get; set; }
public string LastName
{ get; set; }
public string HomeNumber
{ get; set; }
}
Here is your mapping, you have to create a mapping in both directions from dm->vm and vm->dm.
From what I've seen when using Automapper is that if you map from object A to B and B has a property which A doesn't have, it will be reset. So when I create the map I direct it to ignore those missing properties. I'm not a Automapper expert so I may be using it wrong.
Mapping
Mapper.CreateMap<Person, PersonViewModel>();
// Automapper will reset values in dest which don't exist in source, so be sure to ignore them!
Mapper.CreateMap<PersonViewModel, Person>()
.ForMember(dest => dest.HomeNumber, opt => opt.Ignore());
Finally usage:
Person p = new Person()
{
FirstName = "First",
LastName = "Last",
Address1 = "add 1",
Address2 = "add 2"
};
PersonViewModel pvm = Mapper.Map<Person, PersonViewModel>(p);
// Map to a new person
Person p2 = Mapper.Map<PersonViewModel, Person>(pvm);
// Map to the existing person just to update it
Person p3 = new Person()
{
HomeNumber = "numberHere"
};
// This will update p3
Mapper.Map<PersonViewModel, Person>(pvm, p3);
Because of the exclusion, this is obviously less than ideal, but much better than manually doing the whole thing.
Have your view model map one-to-one with your domain model.
Specify Model as argument for the routeValues as below. This means your view model will be initialized with the values from the domain model. Only the sub set of fields in the form will be overwritten in the resulting personViewData.
Update View:
#model ViewModel.PersonView
#using (Html.BeginForm("Update", "Profile", Model, FormMethod.Post))
{
...Put your sub set of the PersonView fields here
}
ProfileController:
public ActionResult Update(string userName)
{
Person person = _unitOfWork.Person.Get().Where(p => p.UserName == userName).FirstOrDefault();
PersonView personView = new PersonView();
Mapper.Map(person, personView);
return View(personView);
}
[HttpPost]
public ActionResult Update(PersonView personViewData)
{
Person person = _unitOfWork.Person.Get().Where(p => p.UserName == personViewData.UserName).FirstOrDefault();
Mapper.Map(personViewData, person);
_unitOfWork.Person.Update(person);
_unitOfWork.Save();
return Json(new { saved = true, status = "" });
}
Why don't you use TryUpdateModel with the form collection.
If your view is editing a person
public class Person
{
public string ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Address { get; set; }
}
And your view is only editing first name and last name, you can do this:
public ActionResult Action(FormCollection form)
{
Person personToUpdate = Repository.GetPerson(form["ID"]);
TryUpdateModel<Person>(personToUpdate, form);
Repository.Update(personToUpdate)
return View();
}
That will only update Person with the items that a part of the form collection. If you don't want a field updated, don't submit it with the form.
What if you have full model but each page uses and updates only the required part? Then you update the business model using complete view data at the last page.
I use a similar approach to yours (in my case Entity Framework) with Entity -> ViewModel -> View but only on views with "complex" entities that have either 1:M or M:M relationships. In most cases I took the low road and went for Entity->View when I have a simple entity.
My ViewModel is defined as Entity+supporting properties: SelectList or MultiSelectList and either a string or List<string>. I'll also use a ViewModel for instances where I have properties I need for the view but may not necessarily need in the entity (database).
Http Get controller methods are straightforward ActionResults with return View(repository.FetchNewViewModel()) for Create or repository.FetchModelById(id) for Edit. In both instances I'm initializing my entities before passing them to the view.
Create([Bind(Exclude = "Entity.EntityId")] ViewModel model) and Edit(ViewModel model) are the Http Post controller methods of Create and Edit. My Edit view has a hidden input field for EntityId to pass it back and forth.
By the time the Http Post method has the viewmodel, I lose all Entity.Relation and ViewModel.(Multi)SelectList values. I have to rebuild the object if I want my view to display properly:
`
try
{
var tags = model.TagIds; // List<string> or <int> depending on your Id type
if (model.TagsList == null) // It will be
{
model.TagsList = _repository.FetchSelectedTags(tags); // Build a new SelectList
}
if (!ModelState.IsValid)
{
return View(model);
}
_repository.Add(model.Article, tags); // or Save() for Edit
}
catch
{
return View(model); // Generally means something screwed in the repository class
}
return RedirectToAction("Index");
`
There is maybe 30% of my entity base using a ViewModel so I definitely only use it as needed. If you have complex views and model data in most instances you can probably break it down to smaller views.
Right now i´m working on a large project using S#arp Architecture and im also using the approach:
Model -> ViewModel -> Model
I use the ViewModel for the Binding part and Validations, the other approach is to use the Model Directly (with tryUpdateModel / UpdateModel which we used during the prototype develop) but for complex scenarios we end up handling special situation like SelectLists/Checkbox/Projections/HMAC Validations in a little ViewModel anyway and using a lot of Request.Form["key"] =( , the other drawback is handling the errors situations where you want to repopulate the form with the user input, i found it a little more complicated using the Model directly (using a ViewModel we take a lot of advantage of ModelState attempted value, saving us a couple of trips to the DB, anyone who have faced this scenario will know what i mean).
This approach is a bit time consuming, just like you said, you end up matching properties, but in my opinion is the way to go for complex forms.
It worth mentioning that we just use ViewModels for the Create/Edit scenarios, for almost everything else we use directly the model.
I have not use autommapers so far, but definitely i ll give it a try.

Resources