validate required field depend on other field in model MVC - asp.net-mvc

I want create model that will validate required field in model that depend on other field condition.
public class FixedDeposit
{
public int DebitAmount { get; set; }
public string PAN { get; set; }
}
Now if the DebitAmount is greater than 50,000 then PAN field is must be required.

You can implement IValidatableObject
public class FixedDeposit : IValidatableObject
{
public int DebitAmount { get; set; }
public string PAN { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (DebitAmount > 50000 && string.IsNullOrEmpty(PAN))
{
yield return new ValidationResult("PAN required for debits > 50,000.", new [] { "PAN" } );
}
}
}
http://weblogs.asp.net/scottgu/class-level-model-validation-with-ef-code-first-and-asp-net-mvc-3

You can also use MVC Foolproof validation package. This package provides you with many conditional validations in the form of annotations.
Complete list is here:
http://foolproof.codeplex.com/
You can add this library to your VS project as a package:
And, for your FixedPayment class, it should look something like this:
using Foolproof;
public class FixedDeposit
{
public int DebitAmount { get; set; }
[RequiredIf("DebitAmount", Operator.GreaterThan, 50000)]
public string PAN { get; set; }
}
Alternate code
using Foolproof;
public class FixedDeposit
{
public int DebitAmount { get; set; }
private bool _panRequired { get { return DebitAmount > 50000; } }
[RequiredIf("_panRequired", true, ErrorMessage="PAN is required if Debit Amount is greater than 50000")]
public string PAN { get; set; }
}

There are two options which you can use.
The first is the very easy to use and quite concise ExpressiveAnnotations JS library developed by Jaroslaw Waliszko. Follow this link to https://github.com/jwaliszko/ExpressiveAnnotations for more information. This library allows you to perform different conditional validations.
Similarly to Foolproof it is added to your Visual Studio environment through adding the NuGet package. Once added, within your model add the using statement using ExpressiveAnnotations.Attributes; Then simply use the RequiredIf declaration to do what you need. For example:
public class FixedDeposit
{
public int DebitAmount { get; set; }
[RequiredIf("DebitAmount >= 50000")]
public string PAN { get; set; }
}
The second option is to use ModelState.AddModelError(). This is done within your controller. Simply create a new method:
private void ValidateRequiredFields(modelname)
{
if(modelname.DebitAmount >= 50000)
{
if(modelname.PAN == null)
{
ModelState.AddModelError("PAN", "Place whatever error message you want here");
}
}
}
Next you place a reference to your validation method in whichever view method you want this to be called. The line to reference is ValidateRequiredFields(ModelName);

public class RequiredIfAttribute : RequiredAttribute
{
private String PropertyName { get; set; }
private Object DesiredValue { get; set; }
public RequiredIfAttribute(String propertyName, Object desiredvalue)
{
PropertyName = propertyName;
DesiredValue = desiredvalue;
}
protected override ValidationResult IsValid(object value, ValidationContext context)
{
Object instance = context.ObjectInstance;
Type type = instance.GetType();
Object proprtyvalue = type.GetProperty(PropertyName).GetValue(instance, null);
if (proprtyvalue.ToString() == DesiredValue.ToString())
{
ValidationResult result = base.IsValid(value, context);
return result;
}
return ValidationResult.Success;
}
}
Usage
[RequiredIf("DebitAmount",50000, ErrorMessage = "PAN field is required")]
public string PAN
{get;set;
}

Related

How Can I Use Custom Validation Attributes on Child Models of a DB Entity?

Summary:
I want a data annotation validator to reference another property in the same class (TitleAuthorAndPublishingConfiguration).
However, DB.SaveChanges() is not being called on this class directly. Rather it is being called on the parent of this class (WebsiteConfiguration).
Therefore validationContext.ObjectType is returning WebsiteConfiguration and I am unable to refer to properties of TitleAuthorAndPublishingConfiguration within the data annotation validator.
WebsiteConfiguration.cs
public class WebsiteConfiguration
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
public TitleAuthorAndPublishingConfiguration TitleAuthorAndPublishing { get; set; }
public BookChaptersAndSectionsConfiguration BookChaptersAndSections { get; set; }
public SocialMediaLoginsConfiguration SocialMediaLogins { get; set; }
public TagGroupsConfiguration TagGroups { get; set; }
}
public class TitleAuthorAndPublishingConfiguration
{
public string BookTitle { get; set; }
public bool IsPublished { get; set; }
// how do I access a property of current model when calling DB.SaveChanges() on parent?
[RequiredIfOtherFieldIsEnabled("IsPublished")]
public string Publisher { get; set; }
}
// ... and other sub models...
ApplicationDbContext.cs
DbSet<WebsiteConfiguration> WebsiteConfiguration {get;set;}
Example Update Code
public void SeedWebsiteConfiguration()
{
var titleAuthorAndPublishingConfiguration = new TitleAuthorAndPublishingConfiguration()
{
// seed values
};
var bookChaptersAndSectionsConfiguration = new BookChaptersAndSectionsConfiguration()
{
// seed values
};
var socialMediaLoginConfiguration = new SocialMediaLoginsConfiguration()
{
// seed values
};
var tagGroupsConfiguration = new TagGroupsConfiguration()
{
// seed values
};
var websiteConfiguration = new WebsiteConfiguration()
{
TitleAuthorAndPublishing = titleAuthorAndPublishingConfiguration,
BookChaptersAndSections = bookChaptersAndSectionsConfiguration,
SocialMediaLogins = socialMediaLoginConfiguration,
TagGroups = tagGroupsConfiguration
};
DB.WebsiteConfiguration.Add(websiteConfiguration);
DB.SaveChanges();
}
Validator Code
public class RequiredIfOtherFieldIsEnabledAttribute : ValidationAttribute
{
private string _ifWhatIsEnabled { get; set; }
public RequiredIfOtherFieldIsEnabledAttribute(string IfWhatIsEnabled)
{
_ifWhatIsEnabled = IfWhatIsEnabled;
}
protected override ValidationResult IsValid(object currentPropertyValue, ValidationContext validationContext)
{
var isEnabledProperty = validationContext.ObjectType.GetProperty(_ifWhatIsEnabled);
if (isEnabledProperty == null)
{
return new ValidationResult(
string.Format("Unknown property: {0}", _ifWhatIsEnabled)
);
}
var isEnabledPropertyValue = (bool)isEnabledProperty.GetValue(validationContext.ObjectInstance, null);
if (isEnabledPropertyValue == true)
{
if (String.IsNullOrEmpty(currentPropertyValue.ToString()))
{
return new ValidationResult(String.Format("This field is required if {0} is enabled", isEnabledProperty));
}
}
return ValidationResult.Success;
}
}
Questions
Is there a way for me to access child model properties from validationContext?
Am I misguided in my approach? Is there a better way to store multiple models as part of a larger model in a single DB table?
I was hoping not to have multiple config tables and calls to the DB. (There are 4 child models in this example, but there may be 10+ in the next app.)
The setup above meets my needs in so many ways. But I don't want to give up the functionality of DataAnnotations on the sub models!
Bonus Question
I have come across a few posts like this one:
How can I tell the Data Annotations validator to also validate complex child properties?
But that is 4 years old, and I'm wondering if anything has changed since then.
Am I trying to do something that is basically impossible (or at least very difficult)?
Am I trying to do something that is basically impossible (or at least
very difficult)?
No, there is a very simple solution that integrates perfectly with the framework and technologies using DataAnnotations.
You can create a custom ValidationAttribute that is called by EF Validation and call Validator.TryValidateObject inside. This way, when CustomValidation.IsValid is called by EF you launch child complex object validation by hand and so on for the whole object graph. As a bonus, you can gather all errors thanks to CompositeValidationResult.
i.e.
using System;
using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;
public class Program
{
public static void Main() {
var person = new Person {
Address = new Address {
City = "SmallVille",
State = "TX",
Zip = new ZipCode()
},
Name = "Kent"
};
var context = new ValidationContext(person, null, null);
var results = new List<ValidationResult>();
Validator.TryValidateObject(person, context, results, true);
PrintResults(results, 0);
Console.ReadKey();
}
private static void PrintResults(IEnumerable<ValidationResult> results, Int32 indentationLevel) {
foreach (var validationResult in results) {
Console.WriteLine(validationResult.ErrorMessage);
Console.WriteLine();
if (validationResult is CompositeValidationResult) {
PrintResults(((CompositeValidationResult)validationResult).Results, indentationLevel + 1);
}
}
}
}
public class ValidateObjectAttribute: ValidationAttribute {
protected override ValidationResult IsValid(object value, ValidationContext validationContext) {
var results = new List<ValidationResult>();
var context = new ValidationContext(value, null, null);
Validator.TryValidateObject(value, context, results, true);
if (results.Count != 0) {
var compositeResults = new CompositeValidationResult(String.Format("Validation for {0} failed!", validationContext.DisplayName));
results.ForEach(compositeResults.AddResult);
return compositeResults;
}
return ValidationResult.Success;
}
}
public class CompositeValidationResult: ValidationResult {
private readonly List<ValidationResult> _results = new List<ValidationResult>();
public IEnumerable<ValidationResult> Results {
get {
return _results;
}
}
public CompositeValidationResult(string errorMessage) : base(errorMessage) {}
public CompositeValidationResult(string errorMessage, IEnumerable<string> memberNames) : base(errorMessage, memberNames) {}
protected CompositeValidationResult(ValidationResult validationResult) : base(validationResult) {}
public void AddResult(ValidationResult validationResult) {
_results.Add(validationResult);
}
}
public class Person {
[Required]
public String Name { get; set; }
[Required, ValidateObject]
public Address Address { get; set; }
}
public class Address {
[Required]
public String Street1 { get; set; }
public String Street2 { get; set; }
[Required]
public String City { get; set; }
[Required]
public String State { get; set; }
[Required, ValidateObject]
public ZipCode Zip { get; set; }
}
public class ZipCode {
[Required]
public String PrimaryCode { get; set; }
public String SubCode { get; set; }
}

Data Annotation Always Searches Parent Model for Property

Update
I have since realised the underlying cause of this problem, and have detailed it in another question, here: How Can I Use Custom Validation Attributes on Child Models of a DB Entity?
I have a WebsiteConfiguration model that consists of a number of sub models, broken down as such for convenience.
public class WebsiteConfiguration
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
public TitleAuthorAndPublishingConfiguration TitleAuthorAndPublishing { get; set; }
public BookChaptersAndSectionsConfiguration BookChaptersAndSections { get; set; }
public SocialMediaLoginsConfiguration SocialMediaLogins { get; set; }
public TagGroupsConfiguration TagGroups { get; set; }
}
I am trying to add a DataAnnotation to one of the sub models, making certain properties required if another is marked as true. Like this:
public class SocialMediaLoginsConfiguration
{
public bool Initialised { get; set; }
public bool IsLoginWithFacebookEnabled { get; set; }
[RequiredIfEnabled("IsLoginWithFacebookEnabled")]
public string LoginWithFacebookAppID { get; set; }
[RequiredIfEnabled("IsLoginWithFacebookEnabled")]
public string LoginWithFacebookAppSecret { get; set; }
}
The DataAnnotation code is:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true, Inherited = false)]
public class RequiredIfEnabledAttribute : ValidationAttribute
{
private string _ifWhatIsEnabled { get; set; }
public RequiredIfEnabledAttribute(string IfWhatIsEnabled)
{
_ifWhatIsEnabled = IfWhatIsEnabled;
}
protected override ValidationResult IsValid(object currentPropertyValue, ValidationContext validationContext)
{
var isEnabledProperty = validationContext.ObjectType.GetProperty(_ifWhatIsEnabled);
if (isEnabledProperty == null)
{
return new ValidationResult(
string.Format("Unknown property: {0}", _ifWhatIsEnabled)
);
}
var isEnabledPropertyValue = (bool)isEnabledProperty.GetValue(validationContext.ObjectInstance, null);
if (isEnabledPropertyValue == true)
{
if (String.IsNullOrEmpty(currentPropertyValue.ToString()))
{
return new ValidationResult(String.Format("This field is required if {0} is enabled", isEnabledProperty));
}
}
return ValidationResult.Success;
}
}
When I attempt to get the value of IsLoginWithFacebookEnabled it looks for this property in the WebsiteConfiguration class, rather than the SocialMediaLoginsConfiguration. Even though the annoted property is in the latter.
How can I make it look for the property within the same class as the annotation?
Update
I think this is happening because I am calling DB.SaveChanges() on the WebsiteConfiguration, like this:
public void SeedWebsiteConfiguration()
{
var titleAuthorAndPublishingConfiguration = new TitleAuthorAndPublishingConfiguration()
{
// seed values
};
var bookChaptersAndSectionsConfiguration = new BookChaptersAndSectionsConfiguration()
{
// seed values
};
var socialMediaLoginConfiguration = new SocialMediaLoginsConfiguration()
{
// seed values
};
var tagGroupsConfiguration = new TagGroupsConfiguration()
{
// seed values
};
var websiteConfiguration = new WebsiteConfiguration()
{
TitleAuthorAndPublishing = titleAuthorAndPublishingConfiguration,
BookChaptersAndSections = bookChaptersAndSectionsConfiguration,
SocialMediaLogins = socialMediaLoginConfiguration,
TagGroups = tagGroupsConfiguration
};
DB.WebsiteConfiguration.Add(websiteConfiguration);
DB.SaveChanges();
}
But I don't want to create separate DB tables for each of the sub models. I'd like them stored together in one table, but in the code I'd like to manage them as sub models.

Object reference not set to an instance of an object.

i have 3 model:
1st one:
public class CreateFieldModel
{
public FieldModel fm { get; set; }
public CategoryModel cm { get; set; }
}
2nd one:
public class FieldModel
{
public string field_Name { get; set; }
public InputTypeModel itm { get; set; }
public string input1 { get; set; }
public string input2 { get; set; }
public string input3 { get; set; }
public string input4 { get; set; }
public List<InputTypeModel> inputs { get; set; }
}
3rd One:
public class InputTypeModel
{
public string inputTypeName { get; set; }
public string inputTypeDesc { get; set; }
}
2 methods:
1st One:
public List<InputTypeModel> getInputTypes()
{
var inptypes = edu.InputTypes;
List<InputTypeModel> listInputTypes = new List<InputTypeModel>();
foreach (var inpType in inptypes)
{
listInputTypes.Add(new InputTypeModel { inputTypeName = inpType.Input_Type_Name, inputTypeDesc = inpType.Input_Type_Description });
}
return listInputTypes;
}
when this method executes listInputTypes has three different values.. i check it by debugging.. so no roblem here. This methos is under the class FormManagement.. I am calling this method from the following action method:
[HttpGet]
public ActionResult createNewField(CreateFieldModel cfm, string fcode)
{
FormManagement ffm = new FormManagement();
cfm.fm.inputs = ffm.getInputTypes();
return View(cfm);
}
when cfm.fm.inputs = ffm.getInputTypes(); executes it is showing "Object reference not set to an instance of an object." message... I am quite beginner to mvc.. please help
Without knowing what you really want to achieve with cfm-parameter in your action, the only thing I can suggest is to check for null references and create new instances before you assign them:
[HttpGet]
public ActionResult createNewField(CreateFieldModel cfm, string fcode)
{
FormManagement ffm = new FormManagement();
if (cfm == null)
{
cfm = new CreateFieldModel();
}
if (cfm.fm == null)
{
cfm.fm = new FieldModel();
}
cfm.fm.inputs = ffm.getInputTypes();
return View(cfm);
}
Of course, this supposes that your not relying on incoming data through your route parameters. If you are, you need to check why the values are not getting passed in, but I'm guessing you don't need it as a parameter in the first place.

How can I enter in date and username automatically when updating storage?

I have the following class that's used by my MVC3 application. I would like
to simplify the updating of the class so that when a new class object is
created then the Created and CreatedBy fields get set automatically.
I'd also like to make it so that the Modified and ModifiedBy fields get
updated automatically.
Is there a way that I could do this?
The class is used in MVCnamespace Storage.Models
{
public class Topic : TableServiceEntity
{
[DisplayName("Partition Key")]
public override string PartitionKey { get; set; }
[DisplayName("Row Key")]
public override string RowKey { get; set; }
[DisplayName("Description")]
public string Description { get; set; }
public DateTime Created { get; set; }
public DateTime Modified { get; set; }
public String CreatedBy { get; set; }
public string ModifiedBy { get; set; }
}
}
Set the defaults in the constructor for the class
public class Topic
{
public Topic()
{
this.Created = DateTime.Now;
this.CreatedBy = UserName;
}
[DisplayName("Partition Key")]
public override string PartitionKey { get; set; }
[DisplayName("Row Key")]
public override string RowKey { get; set; }
[DisplayName("Description")]
public string Description { get; set; }
public DateTime Created { get; set; }
public DateTime Modified { get; set; }
public String CreatedBy { get; set; }
public string ModifiedBy { get; set; }
}
jonathan,
Jason's answer above with the logic contained within the constructors is a perfectly valid and clean way of doing this and I wouldn't argue with that (and have done it myself for more 'static' properties). However, given that there could be a timelapse between the creation of the object and the actual save, then you may also want to consider putting this logic into your controller (or service layer).
this would look roughly like this:
public ActionResult Create(MyCreateViewModel viewModel)
{
if (ModelState.IsValid)
{
viewModel.Entity.Created = DateTime.UtcNow;
_myService.Insert(viewModel.Entity);
_myService.SaveChanges();
return this.RedirectToAction(x => x.Index());
} else {
PopulateViewModel(viewModel);
return View(viewModel);
}
}
likewise, you may have a LastEdit datetime that you want to track. use the Edit action similarly:
public ActionResult Edit(MyEditViewModel viewModel)
{
if (ModelState.IsValid)
{
viewModel.Entity.LastEditDate= DateTime.UtcNow;
_myService.AttachAndUpdate(viewModel.Entity);
_myService.SaveChanges();
return this.RedirectToAction(x => x.Index());
} else {
PopulateViewModel(viewModel);
return View(viewModel);
}
}
just another approach to ensure that datetime related properties are truly reflected.
In this solution i think you may have to make big change in your Repository/Service layer
define an Interface like :
public interface IHistoryLog
{
DateTime Created { get; set; }
DateTime Modified { get; set; }
string CreatedBy { get; set; }
string ModifiedBy { get; set; }
}
then:
public class Topic:IHistoryLog
{
// Implement interface..
}
then create a generic service class:
public abstract class CRUDService<TModel>
{
protected CRUDService(DataContext dataContext)
{
// data context to do generic CRUD stuff
}
public virtual Save(TModel model)
{
if(model is IHistoryLog)
{
// assign Createdby and Created
}
}
public virtual Update(TModel model)
{
if(model is IHistoryLog)
{
// assign ModifiedBy and Modified
}
}
}

Disable validation on certain fields

I've got a ViewModel for adding a user with properties: Email, Password, ConfirmPassword with Required attribute on all properties. When editing a user I want the Password and ConfirmPassword properties not to be required.
Is there a way to disable validation for certain properties in different controller actions, or is it just best to create a seperate EditViewModel?
I like to break it down and make a base model with all the common data and inhierit for each view:
class UserBaseModel
{
int ID { get; set; }
[Required]
string Name { get; set; }
[Required]
string Email { get; set; }
// etc...
}
class UserNewModel : UserBaseModel
{
[Required]
string Password { get; set; }
[Required]
string ConfirmPassword { get; set; }
}
class UserEditModel : UserBaseModel
{
string Password { get; set; }
string ConfirmPassword { get; set; }
}
Interested to know if there is a better way as well although this way seems very clean an flexible.
You could write a custom attribute that can test a condition and either allow an empty field or not allow it.
The below is a simple demo i put together for the guys here. You'll need to modify to suit your purposes/
using System.ComponentModel.DataAnnotations;
namespace CustomAttributes
{
[System.AttributeUsage(System.AttributeTargets.Property)]
public class MinimumLength : ValidationAttribute
{
public int Length { get; set; }
public MinimumLength()
{
}
public override bool IsValid(object obj)
{
string value = (string)obj;
if (string.IsNullOrEmpty(value)) return false;
if (value.Length < this.Length)
return false;
else
return true;
}
}
}
Model;
using CustomAttributes;
namespace Models
{
public class Application
{
[MinimumLength(Length=20)]
public string name { get; set; }
}
}
Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(Application b)
{
ViewData["Message"] = "Welcome to ASP.NET MVC!";
if (ModelState.IsValid)
{
return RedirectToAction("MyOtherAction");
}
return View(b);
}
enter code here

Resources