Multiple custom validation attributes for the mvc class

I am creating an example for a better understanding.

[CustomValidator("Property1","Property2", ErrorMessage= "Error1")] [CustomValidator("Property3","Property4", ErrorMessage= "Error1")] public class MyViewModel { public string Property1 {get; set;} public string Property2 {get; set;} public string Property3 {get; set;} public string Property4 {get; set;} } [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)] public class CustomValidator : ValidationAttribute { All the required stuff is written. } 

Only the second validator (or the last one from the list) is launched and ignores the first. I am not sure if this is the right approach for this scenario. Any suggestions?

+4
source share
4 answers

if you are using linq for sql why not try something like this

add a rule violation class to eliminate rule violations

 public class RuleViolation { public string ErrorMessage { get; private set; } public string PropertyName { get; private set; } public RuleViolation(string errorMessage) { ErrorMessage = errorMessage; } public RuleViolation(string errorMessage, string propertyName) { ErrorMessage = errorMessage; PropertyName = propertyName; } } 

now in your data class

 [Bind(Exclude="ID")] public partial class Something { public bool IsValid { get { return (GetRuleViolations().Count() == 0); } } public IEnumerable<RuleViolation> GetRuleViolations() { if (String.IsNullOrEmpty(Name.Trim())) yield return new RuleViolation("Name Required", "Name"); if (String.IsNullOrEmpty(LocationID.ToString().Trim())) yield return new RuleViolation("Location Required", "LocationID"); yield break; } partial void OnValidate(ChangeAction action) { if (!IsValid) throw new ApplicationException("Rule violations prevent saving"); } } 

and in your controller methods for updating, use the updatemodel method to change the properties

 Something something = somethingRepo.GetSomething(id); try { //update something UpdateModel(something); somethingRepo.Save(); return RedirectToAction("Index"); } catch { ModelState.AddRuleViolations(something.GetRuleViolations()); return View(something); } 

that way you can just add rules to your data class as it changes and it will appear in your updates, etc.

+1
source

I found another question that answers this. You must override Attribute.TypeId .

Validation custom attribute with multiple instance problem

+1
source

you really don't need all these codes to use data annotations by creating a metaData class for your model link text

which should set you on the right road, also read the html helpers and friend classes (this is what they call em)

0
source

I had the same problem.

I came up with the following solution.

Your POCO class can implement the IValidatableObject interface.

This requires you to implement the following method.

  public virtual IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { // return list of appropriate ValidationResult object var customResult = new List<ValidationResult>(); customResult.Add(new ValidationResult("message", new List<string>(){"Property1"}); } 

Here you can put any validation logic. It also takes precedence over a class attribute. A class level attribute can only be displayed in ValidationSummary (they are not associated with any property). In contrast to it, you can set certain elements when returning ValidationResult. This allows you to display verification information related to the specific control to which the message relates.

0
source

Source: https://habr.com/ru/post/1302169/


All Articles