Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One of two properties is required from the data model

Let's say I have a Person class with FirstName and LastName. I want that the user must enter at least one of the two values in the UI but he may not have to enter each of them.

If I place the Required attribute / data annotation on each of them, that makes both of them required.

How do I make a server side validation (with client side validation, too) for this rule?

like image 518
Water Cooler v2 Avatar asked Dec 17 '12 13:12

Water Cooler v2


People also ask

What are data properties?

Data properties are characteristics of GIS attribute systems and values whose design and format impacts analytical and computational processing. Geospatial data are expressed at conceptual, logical, and physical levels of database abstraction intended to represent geographical information.

What are the 4 different types of data models?

There are four types of data models: Hierarchical model, Network model, Entity-relationship model, Relational model.

What are field properties in a database?

The properties of a field describe the characteristics and behavior of data added to that field. A field's data type is the most important property because it determines what kind of data the field can store.

What is data model and types of data model?

The three primary data model types are relational, dimensional, and entity-relationship (E-R). There are also several others that are not in general use, including hierarchical, network, object-oriented, and multi-value.


1 Answers

You could use a custom attribute for this. In short, the custom attribute will retrieve both values and then ensure at least one has a value. See this page for more information. Here is an example (untested code):

[AttributeUsage(AttributeTargets.Property, AllowMultiple =false, Inherited = false)]
  public class ValidatePersonName: ValidationAttribute
  {
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
      string FirstName = (string)validationContext.ObjectType.GetProperty("FirstName").GetValue(validationContext.ObjectInstance, null);

      string LastName = (string)validationContext.ObjectType.GetProperty("LastName").GetValue(validationContext.ObjectInstance, null);

  //check at least one has a value
  if (string.IsNullOrEmpty(FirstName) && string.IsNullOrEmpty(LastName))
        return new ValidationResult("At least one is required!!");

      return ValidationResult.Success;
    }
  }

Usage:

class Person{

 [ValidatePersonName]
 FirstName{get;set;}

 LastName{get;set;}
}
like image 57
Ulises Avatar answered Nov 16 '22 01:11

Ulises