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?
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.
There are four types of data models: Hierarchical model, Network model, Entity-relationship model, Relational model.
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.
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.
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;}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With