I have an ASP.NET MVC website that is passing ViewModels up to a WebAPI Service in order to perform CRUD operations on objects in the database using Entity Framework code first.
One of my Domain Entity Objects is a Business, which has business information, an address, a primary contact, and secondary contact. The thing is, the secondary contact object is not required since not all companies will have a secondary contact. I have setup the ID field as nullable, but when I attempt to save a new business record into the database that doesn't have a secondary contact object, it is giving me entity validation errors that the Secondary Contact record fields are required.
Does anyone know how to stop this error so I can save the business entity in the database without a secondary contact?
Below is the related code. I am using automapper to map between my viewmodels and models.
Domain Business Object
public class Business
{
public Guid PrimaryContactId { get; set; }
[ForeignKey("PrimaryContactId")]
[Required]
public virtual Contact PrimaryContact { get; set; }
public Guid? SecondaryContactId { get; set; }
[ForeignKey("SecondaryContactId")]
public virtual Contact SecondaryContact { get; set; }
[Key]
public Guid Id { get; set; }
[Required]
[MaxLength(100)]
public string CompanyName { get; set; }
[MaxLength(100)]
public string CompanyWebsite { get; set; }
[Required]
[MaxLength(100)]
public string Industry { get; set; }
[Required]
public NumberOfEmployees NumberOfEmployees { get; set; }
[Required]
public CommunicationPreference CommunicationPreference { get; set; }
public Guid AddressId { get; set; }
[ForeignKey("AddressId")]
[Required]
public virtual Address Address { get; set; }
}
Business View Model
public class BusinessViewModel
{
public Guid PrimaryContactId { get; set; }
public PrimaryContactViewModel PrimaryContact { get; set; }
public Guid? SecondaryContactId { get; set; }
public SecondaryContactViewModel SecondaryContact { get; set; }
public Guid Id { get; set; }
[DisplayName("Company Name")]
[Required]
[MinLength(3, ErrorMessage = "Your {0} must be at least {1} characters long")]
[MaxLength(100, ErrorMessage = "Your {0} must be no more than {1} characters")]
public string CompanyName { get; set; }
[DisplayName("Company Website")]
[MinLength(3, ErrorMessage = "Your {0} must be at least {1} characters long")]
[MaxLength(100, ErrorMessage = "Your {0} must be no more than {1} characters")]
public string CompanyWebsite { get; set; }
[DisplayName("Industry")]
[Required]
[MinLength(3, ErrorMessage = "Your {0} must be at least {1} characters long")]
[MaxLength(100, ErrorMessage = "Your {0} must be no more than {1} characters")]
public string Industry { get; set; }
[DisplayName("Number of Employees")]
[Required]
public NumberOfEmployees NumberOfEmployees { get; set; }
[DisplayName("Communication Preference")]
[Required]
public CommunicationPreference CommunicationPreference { get; set; }
public Guid AddressId { get; set; }
[Required]
public AddressViewModel Address { get; set; }
}
Domain Contact Object
public class Contact
{
[Key]
public Guid Id { get; set; }
[Required]
public Salutations? Prefix { get; set; }
[Required]
[MaxLength(100)]
public string FirstName { get; set; }
[Required]
[MaxLength(100)]
public string LastName { get; set; }
[Required]
[MaxLength(100)]
public string JobTitle { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
[MaxLength(100)]
public string Email { get; set; }
[Required]
[MaxLength(100)]
public string Phone { get; set; }
[MaxLength(100)]
public string PhoneExtension { get; set; }
}
Base Contact View Model
public class BaseContactViewModel
{
public Guid Id { get; set; }
[DisplayName("Primary Contact Prefix")]
public virtual Salutations Prefix { get; set; }
[DisplayName("Primary Contact First Name")]
[MinLength(3, ErrorMessage = "Your {0} must be at least {1} characters long")]
[MaxLength(100, ErrorMessage = "Your {0} must be no more than {1} characters")]
public virtual string FirstName { get; set; }
[DisplayName("Primary Contact Last Name")]
[MinLength(3, ErrorMessage = "Your {0} must be at least {1} characters long")]
[MaxLength(100, ErrorMessage = "Your {0} must be no more than {1} characters")]
public virtual string LastName { get; set; }
[DisplayName("Primary Contact Job Title")]
[MinLength(3, ErrorMessage = "Your {0} must be at least {1} characters long")]
[MaxLength(100, ErrorMessage = "Your {0} must be no more than {1} characters")]
public virtual string JobTitle { get; set; }
[DisplayName("Primary Contact Email Address")]
[DataType(DataType.EmailAddress)]
[MinLength(3, ErrorMessage = "Your {0} must be at least {1} characters long")]
[MaxLength(100, ErrorMessage = "Your {0} must be no more than {1} characters")]
public virtual string Email { get; set; }
[DisplayName("Primary Contact Phone")]
[DataType(DataType.PhoneNumber)]
[MinLength(3, ErrorMessage = "Your {0} must be at least {1} characters long")]
[MaxLength(100, ErrorMessage = "Your {0} must be no more than {1} characters")]
public virtual string Phone { get; set; }
[DisplayName("Primary Contact Extension")]
[MinLength(3, ErrorMessage = "Your {0} must be at least {1} characters long")]
[MaxLength(100, ErrorMessage = "Your {0} must be no more than {1} characters")]
public virtual string PhoneExtension { get; set; }
}
Secondary Contact View Model
public class SecondaryContactViewModel : BaseContactViewModel
{
[DisplayName("Secondary Contact Prefix")]
public override Salutations Prefix { get; set; }
[DisplayName("Secondary Contact First Name")]
public override string FirstName { get; set; }
[DisplayName("Secondary Contact Last Name")]
public override string LastName { get; set; }
[DisplayName("Secondary Contact Job Title")]
public override string JobTitle { get; set; }
[DisplayName("Secondary Contact Email Address")]
public override string Email { get; set; }
[DisplayName("Secondary Contact Phone")]
public override string Phone { get; set; }
[DisplayName("Secondary Contact Extension")]
public override string PhoneExtension { get; set; }
}
Method that does the EF saving
public async Task<bool> CreateBusinessAsync(BusinessViewModel businessViewModel)
{
try
{
// TODO: Move mapping to some common place?
Mapper.CreateMap<BusinessViewModel, Business>();
Mapper.CreateMap<BaseContactViewModel, Contact>();
Mapper.CreateMap<AddressViewModel, Address>();
Business business = Mapper.Map<Business>(businessViewModel);
//TODO: See why EntityFramework isn't automatically putting in GUIDs
business.Id = Guid.NewGuid();
business.Address.Id = Guid.NewGuid();
business.PrimaryContact.Id = Guid.NewGuid();
// Attach the objects so they aren't saved as new entries
db.States.Attach(business.Address.State);
db.Countries.Attach(business.Address.Country);
//TODO: See why entity framework isn't automatically saving records
var bus = db.Businesses.Add(business);
var primary = db.Contacts.Add(business.PrimaryContact);
if (!String.IsNullOrEmpty(business.SecondaryContact.FirstName))
{
business.SecondaryContact.Id = Guid.NewGuid();
db.Contacts.Add(business.SecondaryContact);
}
else
{
business.SecondaryContact = null;
}
var address = db.Addresses.Add(business.Address);
int rowsAffected = await db.SaveChangesAsync();
if (bus != null && rowsAffected > 0)
{
return true;
}
else
{
return false;
}
}
catch (Exception e)
{
//TODO: Add exception logger
string error = e.Message;
return false;
}
}
Please let me know if it would be useful to see any other classes. Thanks.
I had a similar issue before and the way I fixed it was by taking the foreign key data annotation off of the property and using fluent-api. Using fluent-api I just labeled the correct side of the relationship as optional.
You can just make the data type to nullable based on documentation
public class Foo {
// ...... Some property
[ForeignKey("tagId")]
public ICollection<SomeModel>? data {get; set;}
}
This will make the property not validated and return validated result. Using Model.IsValid
Related
Below is my State Model class.
public class State
{
[Key]
public int StateId { get; set; }
public string StateName { get; set; }
public virtual ICollection<City> Cities { get; set; }
}
Below is my City Model Class base state, city will fill.
public class City
{
[Key]
public int CityId { get; set; }
public string CityName { get; set; }
[ForeignKey("State")]
public int StateId { get; set; }
public virtual State State { get; set; }
}
Below is my Registration model class for the registration form which calls State city.
public class Registration
{
[Key]
public int Sno { get; set; }
[Required(ErrorMessage = "Name is required.")]
[Display(Name = "Full name")]
public string Fullname { get; set; }
[Display(Name = "Email Id")]
[Required(ErrorMessage = "Email is required.")]
public string EmailId { get; set; }
[Required(ErrorMessage = "Password is required.")]
public string Password { get; set; }
[Required(ErrorMessage = "Mobile is required.")]
public string Mobile { get; set; }
[Required(ErrorMessage = "Address is required.")]
public string Address { get; set; }
public int SelectedStateId { get; set; }
public int SelectedCityId { get; set; }
[Required(ErrorMessage = "Entity is required.")]
public string EntityType { get; set; }
public string Website { get; set; }
public string PinCode { get; set; }
public string accountactivated { get; set; }
public int RoleId { get; set; }
[Display(Name = "New Password")]
[NotMapped]
public string NewPassword { get; set; }
[Display(Name = "Confirm New Password")]
[NotMapped] // Does not effect with your database
[System.Web.Mvc.Compare("NewPassword", ErrorMessage = "Password not match")]
public string ConfirmNewPassword { get; set; }
}
My question is how should i have to call state and city cascading drop down list in my Registration Model class to generate scaffolding for registration page with dependent drop down list.
i have 3 models
public class UsersModel
{
[Key]
public int UserId { get; set; }
[Required]
[StringLength(100, ErrorMessage = "Invalid Name Minimum Length is 5", MinimumLength = 5)]
public string Name { get; set; }
//20150090
public int? student_ID { get; set; }
[Display(Name = "transcript")]
public string transcript { get; set; }
[Required]
[EmailAddress]
public string Email { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password do not match.")]
public string ConfirmPassword { get; set; }
[Required]
[StringLength(100, ErrorMessage = "Invalid Name Minimum Length is 2", MinimumLength = 2)]
public string Department { get; set; }
[Required]
[Display(Name = "Phone")]
[DataType(DataType.PhoneNumber,ErrorMessage ="Invalid Phone Number")]
[Range(999999999, 9999999999)]
public int Phone { get; set; }
public int type { get; set; }
}
student
public class StudentsModel
{
[Key]
[Display(Name ="ID")]
public int StudentID { get; set; }
[Required]
public string Name { get; set; }
[Required]//20150090
public string student_ID { get; set; }
[Required]
[Display(Name = "Skills")]
public string Skills { get; set; }
[Required]
[Display(Name = "Gpa")]
[Range(1.00, 4.00, ErrorMessage = "It must be in range 0.00 to 4.00 :)")]
public float Gpa { get; set; }
[Required]
[Display(Name = "Leader")]
public string Leader { get; set; }
[Required]
[Display(Name = "transcript")]
public string transcript { get; set; }
[ForeignKey("UserId")]
public int UserId;
public UsersModel Users { get; set; }
[ForeignKey("IdeaId")]
public int? IdeaId;
public IdeaModel Idea { get; set; }
}
Idea
public class IdeaModel
{
[Required]
[Key]
public int IdeaId { get; set; }
[Required]
public string IdeaName { get; set; }
[Required]
public string IdeaDescription { get; set; }
[Required]
public string tools { get; set; }
public int? SetWith { get; set; }
[Required]
public int Prof1 { get; set; }
public int Prof2 { get; set; }
public int Prof3 { get; set; }
}
when i insert to the database user and student and idea
the foreign key in student model inserted with null value
this is the code for insertion
i want the foreign key in student model to inserted automatically
whit the values of primary key in usernodel and idea model how to make this?
public ActionResult RegisterLeader(regall reg)
{
if (ModelState.IsValid)
{
var user= db.Users.Add(reg.users);
var idea = db.Idea.Add(reg.idea);
var stu = db.Students.Add(reg.students[0]);
db.SaveChanges();
return View("RegisterLeaderPost");
//return Registerfinish();
}
}
this model have the three models
public class regall
{
public List<StudentsModel> students { get; set; }
public UsersModel users { get; set; }
public IdeaModel idea { get; set; }
}
You need to set the Idea property of the student so EF knows to make the relationship.
reg.students[0].Idea = reg.idea;
I've created a database according to which the user profile is formed by the following two classes:
public class Usr
{
[Key()]
public int UsrID { get; set; }
public virtual UsrType UsrType { get; set; }
public virtual UsrStatus UsrStatus { get; set; }
[Required]
[MaxLength(100, ErrorMessage = "Email can only contain {0} characters")]
public string UsrEmail { get; set; }
[Required]
[MaxLength(32, ErrorMessage = "Password can only contain {0} characters")]
[MinLength(8, ErrorMessage = "Password must be at least {0} characters")]
public string UsrPassword { get; set; }
}
public class UsrDetails
{
[ForeignKey("UsrID")]
[Required]
public virtual Usr Usr { get; set; }
[Required]
[MaxLength(40, ErrorMessage = "Name can only contain {0} characters")]
public string UsrName { get; set; }
[Required]
[MaxLength(40, ErrorMessage = "Surname can only contain {0} characters")]
public string UsrSurname { get; set; }
[Required]
[MaxLength(20, ErrorMessage = "Country can only contain {0} characters")]
public string UsrCountry { get; set; }
[Required]
[MaxLength(20, ErrorMessage = "City can only contain {0} characters")]
public string UsrCity { get; set; }
[Required]
[MaxLength(40, ErrorMessage = "Street can only contain {0} characters")]
public string UsrStreet { get; set; }
[Required]
public int UsrNum { get; set; }
[Required]
public int UsrPostalCode { get; set; }
}
I want to connect them by having both as primary key the UsrID and I get an error that UsrDetails don't have a primary key because I'm using the foreign key attribute. Any ideas?
You need to declare a key property in UserDetails with the same name that you declare in the ForeignKey attribute:
public class UsrDetails
{
[Key]
public int UsrID{ get; set; }
[ForeignKey("UsrID")]
public virtual Usr Usr { get; set; }
}
All your entities must have a PK property. In this case where you are representing a one to one relationship, the PK of the dependent entity also is the FK. You can check this tutorial in case you need more info.
How do I validate & potentially charge Credit Card details server side (in the Create function below) without saving these details to a database.
Create ActionResult
public ActionResult Create()
{
var model = new Payment();
model.ValidFrom = DateTime.Now;
return View(new Payment());
}
// POST: Payments/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "ID,CardName,CardNumber,ValidFrom,Expires,CardSecurityCode,EmailAddress,ConfrimEmailAddress,Address,City,Country,PostCode")] PaymentViewModel paymentViewModel ,Payment payment)
{
if (ModelState.IsValid)
{
payment = new Payment();
payment.EmailAddress = paymentViewModel.EmailAddress;
payment.ConfrimEmailAddress = paymentViewModel.ConfirmEmailAddress;
payment.Address = paymentViewModel.Address;
payment.City = paymentViewModel.City;
payment.Country = paymentViewModel.Country;
payment.PostCode = paymentViewModel.PostCode;
db.Payments.Add(payment);
db.SaveChanges();
return RedirectToAction("Details", "Payments", new { id = payment.ID });
}
return View(paymentViewModel);
}
Model
public class Payment
{
public int ID { get; set; }
[RegularExpression(#"^[a-zA-Z]+$", ErrorMessage = "Use letters only please")]
public string CardName { get; set; }
// ------------------------------Visa Card ---------------------------------------------//
[RegularExpression(#"^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11})|(4903|4905|4911|4936|6333|6759)[0-9]{12}|(4903|4905|4911|4936|6333|6759)[0-9]{14}|(4903|4905|4911|4936|6333|6759)[0-9]{15}|564182[0-9]{10}|564182[0-9]{12}|564182[0-9]{13}|633110[0-9]{10}|633110[0-9]{12}|633110[0-9]{13}$", ErrorMessage = "Invalid Card Number You Paki")]
public string CardNumber { get; set; }
[Display(Name = "Valid From"), DataType(DataType.Date) DisplayFormat(DataFormatString = "{0:MM}")]
public DateTime ValidFrom { get; set; }
[Display(Name = "Valid From"), DataType(DataType.Date) DisplayFormat(DataFormatString = "{0:MM}")]
public DateTime Expires { get; set; }
public string CardSecurityCode { get; set; }
[Required]
[EmailAddress]
public string EmailAddress { get; set; }
[Compare("EmailAddress", ErrorMessage = "The email and confirmation email do not match.")]
public string ConfrimEmailAddress { get; set; }
[RegularExpression(#"([a-zA-Z0-9\s]+)", ErrorMessage = "Invalid Address")]
public string Address { get; set; }
[RegularExpression(#"^[a-zA-Z]+$", ErrorMessage = "Use letters only please")]
public string City { get; set; }
[RegularExpression(#"^[a-zA-Z]+$", ErrorMessage = "Use letters only please")]
public string Country { get; set; }
[RegularExpression(#"\b\d{5}(?:-\d{4})?\b+", ErrorMessage = "Invalid postcode")]
public string PostCode { get; set; }
}
public class PaymentDBContext : DbContext //controls information in database
{
public DbSet<Payment> Payments { get; set; } //creates a donation database
public System.Data.Entity.DbSet<CharitySite.Models.Charity> Charities { get; set; }
}
I need to be able to retrive the Credit Card numbers without storing them in the database. Our original idea was to validate Credit Card Details client side using Javascript but project requirements dictate that server sided validation is performed.
If you only need to save a part of the information, and use the rest only for validation purposes (eg, validate the number of credit card), then you must use a ViewModel that contains all the information requested on the form, and extract from the ViewModel only the information you need save:
ViewModel:
public class PaymentViewModel
{
public int ID { get; set; }
[RegularExpression(#"^[a-zA-Z]+$", ErrorMessage = "Use letters only please")]
public string CardName { get; set; }
// ------------------------------Visa Card ---------------------------------------------//
[RegularExpression(#"^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11})|(4903|4905|4911|4936|6333|6759)[0-9]{12}|(4903|4905|4911|4936|6333|6759)[0-9]{14}|(4903|4905|4911|4936|6333|6759)[0-9]{15}|564182[0-9]{10}|564182[0-9]{12}|564182[0-9]{13}|633110[0-9]{10}|633110[0-9]{12}|633110[0-9]{13}$", ErrorMessage = "Invalid Card Number You Paki")]
public string CardNumber { get; set; }
[Display(Name = "Valid From"), DataType(DataType.Date) DisplayFormat(DataFormatString = "{0:MM}")]
public DateTime ValidFrom { get; set; }
[Display(Name = "Valid From"), DataType(DataType.Date) DisplayFormat(DataFormatString = "{0:MM}")]
public DateTime Expires { get; set; }
public string CardSecurityCode { get; set; }
[Required]
[EmailAddress]
public string EmailAddress { get; set; }
[Compare("EmailAddress", ErrorMessage = "The email and confirmation email do not match.")]
public string ConfrimEmailAddress { get; set; }
[RegularExpression(#"([a-zA-Z0-9\s]+)", ErrorMessage = "Invalid Address")]
public string Address { get; set; }
[RegularExpression(#"^[a-zA-Z]+$", ErrorMessage = "Use letters only please")]
public string City { get; set; }
[RegularExpression(#"^[a-zA-Z]+$", ErrorMessage = "Use letters only please")]
public string Country { get; set; }
[RegularExpression(#"\b\d{5}(?:-\d{4})?\b+", ErrorMessage = "Invalid postcode")]
public string PostCode { get; set; }
}
Model (only containing fields to save):
public class Payment
{
public int ID { get; set; }
[Required]
[EmailAddress]
public string EmailAddress { get; set; }
[Compare("EmailAddress", ErrorMessage = "The email and confirmation email do not match.")]
public string ConfrimEmailAddress { get; set; }
[RegularExpression(#"([a-zA-Z0-9\s]+)", ErrorMessage = "Invalid Address")]
public string Address { get; set; }
[RegularExpression(#"^[a-zA-Z]+$", ErrorMessage = "Use letters only please")]
public string City { get; set; }
[RegularExpression(#"^[a-zA-Z]+$", ErrorMessage = "Use letters only please")]
public string Country { get; set; }
[RegularExpression(#"\b\d{5}(?:-\d{4})?\b+", ErrorMessage = "Invalid postcode")]
public string PostCode { get; set; }
}
public class PaymentDBContext : DbContext //controls information in database
{
public DbSet<Payment> Payments { get; set; } //creates a donation database
public System.Data.Entity.DbSet<CharitySite.Models.Charity> Charities { get; set; }
}
Create Action:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(PaymentViewModel paymentViewModel)
{
if (ModelState.IsValid)
{
// Some validation on credit card before save payment...
// Save payment
payment = new Payment();
payment.EmailAddress = paymentViewModel.EmailAddress;
payment.ConfirmEmailAddress = paymentViewModel.ConfirmEmailAddress;
payment.Address = paymentViewModel.Address;
payment.City = paymentViewModel.City;
payment.Country = paymentViewModel.Country
payment.PostCode = paymentViewModel.PostCode;
db.Payments.Add(payment);
db.SaveChanges();
return RedirectToAction("Details", "Payments", new { id = payment.ID });
}
return View(paymentViewModel);
}
And change the Model used in your View:
#model [yourNameSpace].paymentViewModel
As far as I am aware there is no legislation actively prohibiting you from storing Credit Card details. Though certain aspects of your implementation may fail PCI compliance. For example, you may store the credit card number and expiry date but this must be in an encrypted form, you may NEVER store the CCV in any form.
Either way it isn't really recommended that you take on the burden of storing CC numbers, unless you have considerable experience and compliance budget. The only advantage I can really see to this is the consumer convenience of not having to repeatedly enter details. Most payment processors should allow you pass details to them for charging. If you choose this approach you may want to look into usage of the SecureString class which will allow you to dispose of details as soon as you have transmitted them to the processor.
I had been struggling with this issue since morning. I have the following class in my domain service.
[MetadataTypeAttribute(typeof(CompanyRecord.CompanyRecordMetadata))]
public partial class CompanyRecord
{
// This class allows you to attach custom attributes to properties
// of the CompanyRecord class.
//
// For example, the following marks the Xyz property as a
// required property and specifies the format for valid values:
// [Required]
// [RegularExpression("[A-Z][A-Za-z0-9]*")]
// [StringLength(32)]
// public string Xyz { get; set; }
internal sealed class CompanyRecordMetadata
{
// Metadata classes are not meant to be instantiated.
private CompanyRecordMetadata()
{
}
public Nullable<char> AccessToClearance { get; set; }
public Nullable<char> AccessToMarketplace { get; set; }
public Nullable<bool> Active { get; set; }
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public Nullable<int> AllotedHDSpace { get; set; }
public string City { get; set; }
public int CompanyID { get; set; }
public Binary CompanyLogo { get; set; }
[Required(ErrorMessage = "Company Name is required and must be unique.")]
public string CompanyName { get; set; }
[Range(1, Int32.MaxValue, ErrorMessage = "Company Type is required.")]
public int CompanyTypeID { get; set; }
[Range(1, Int32.MaxValue, ErrorMessage = "Country is required.")]
public Nullable<int> CountryID { get; set; }
public string Description { get; set; }
//[RegularExpression(pattern: #"[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+(?:[A-Z]{2}|com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum|tv|COM|ORG|NET|GOV|MIL|BIZ|INFO|MOBI|NAME|AERO|JOBS|MUSEUM|TV|Com|Org|Net|Gov|Mil|Biz|Info|Mobi|Name|Aero|Jobs|Museum|Tv)\b", ErrorMessage = "Please provide a valid email address")]
[RegularExpression(pattern: #"(\w[-._\w]*\w#\w[-._\w]*\w\.[a-zA-z]{2,6})", ErrorMessage = "Please provide a valid email address")]
public string EmployeeEmail { get; set; }
//[RegularExpression(pattern: #"[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+(?:[A-Z]{2}|com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum|tv|COM|ORG|NET|GOV|MIL|BIZ|INFO|MOBI|NAME|AERO|JOBS|MUSEUM|TV|Com|Org|Net|Gov|Mil|Biz|Info|Mobi|Name|Aero|Jobs|Museum|Tv)\b", ErrorMessage = "Please provide a valid email address")]
//(\w[-._\w]*\w#\w[-._\w]*\w\.\w{2,3})
[RegularExpression(pattern: #"(\w[-._\w]*\w#\w[-._\w]*\w\.[a-zA-z]{2,6})", ErrorMessage = "Please provide a valid email address")]
[Required(ErrorMessage = "Email is required.")]
public string Email { get; set; }
[StringLength(10, ErrorMessage = "Phone Ext. should not be more than 10 chars.")]
public string EmployeePhoneExt { get; set; }
[StringLength(20, ErrorMessage = "Phone No. should not be more than 20 chars.")]
[RegularExpression(pattern: #"^[0-9\-\(\) ]*[0-9\-\(\)]*$", ErrorMessage = "Please provide a valid Phone No.")]
public string EmployeePhoneNo { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
[Range(0, int.MaxValue, ErrorMessage = "Number of projects should be lower than 2,147,483,647.")]
public Nullable<int> NoOfProjects { get; set; }
public Nullable<int> NoOfUsers { get; set; }
[StringLength(10, ErrorMessage = "Phone Ext. should not be more than 10 chars.")]
public string PhoneExt { get; set; }
[StringLength(20, ErrorMessage = "Phone No. should not be more than 20 chars.")]
[Required(ErrorMessage = "Phone No. is required.")]
[RegularExpression(pattern: #"^[0-9\-\(\) ]*[0-9\-\(\)]*$", ErrorMessage = "Please provide a valid Phone No.")]
public string PhoneNo { get; set; }
[RegularExpression(pattern: #"^[a-zA-Z0-9\-\(\)\* ]*[a-zA-Z0-9\-\(\)\*]*$", ErrorMessage = "Postal codes cant' contain special characters except for -, (, ), * and spaces.")]
public string PostalCode { get; set; }
public string Province { get; set; }
public string Website { get; set; }
public int MarketID { get; set; }
public int AffiliationID { get; set; }
public string CallLetter { get; set; }
}
}
PROBLEM: I need to create a validation rule that woudl require MarketID and Affiliation ID only when CompanyTypeID is equivalent to 1, 3, 5, 9 and 11 is there someone out there who has an idea on how to solve this?
You should use the custom validation.
There are some topics for your question below:
1 http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.customvalidationattribute(vs.95).aspx
2 http://blogs.microsoft.co.il/blogs/bursteg/archive/2009/04/14/net-ria-services-custom-validation.aspx