Cannot convert from interface to class - c#

I had an error in my method when I try to add to the database my interface and it gives me the error,
Argument 1: cannot convert from 'ForumSite.ActionsAndMethods.Registration.IRegistration' to 'ForumSite.Models.User'.
Here is the code in IRegistration:
using ForumSite.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ForumSite.ActionsAndMethods.Registration
{
public interface IRegistration
{
int UserId { get; }
string Email { get; }
string Password { get; }
string FirstName { get; }
string LastName { get; }
DateTime Birthday { get; }
DateTime DateCreated { get; set; }
string MobileNumber { get; }
string Address { get; }
int UserIsDeleted { get; set; }
int UserRoleId { get; set; }
UserRole UserRole { get; }
}
}
And this is the code in my model:
namespace ForumSite.Models
{
using ActionsAndMethods.Registration;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
public partial class User : IRegistration
{
public int UserId { get; set; }
[Display(Name = "Email Address")]
[Required(ErrorMessage = "This field required.")]
[RegularExpression(#"^([a-zA-Z0-9_\-\.]+)#([a-zA-Z]+)\.([a-zA-Z]{2,5})$", ErrorMessage = "Enter Valid Email Address")]
[StringLength(50, MinimumLength = 8, ErrorMessage = "8 to 50 characters only")]
public string Email { get; set; }
[Display(Name = "Password")]
[Required(ErrorMessage = "This field required.")]
[RegularExpression(#"^[a-zA-Z0-9]+$", ErrorMessage = "Alphanumeric characters only")]
[StringLength(50, MinimumLength = 8, ErrorMessage = "8 to 50 characters only")]
public string Password { get; set; }
[Display(Name = "Confirm Password")]
[Required(ErrorMessage = "This field required.")]
[RegularExpression(#"^[a-zA-Z0-9]+$", ErrorMessage = "Alphanumeric characters only")]
[StringLength(50, MinimumLength = 8, ErrorMessage = "8 to 50 characters only")]
public string PasswordConfirm { get; set; }
[Display(Name = "First Name")]
[Required(ErrorMessage = "This field required.")]
[RegularExpression(#"^[a-zA-Z\s]+$", ErrorMessage = "Letters Only.")]
public string FirstName { get; set; }
[Display(Name = "Last Name")]
[Required(ErrorMessage = "This field required.")]
[RegularExpression(#"^[a-zA-Z\s]+$", ErrorMessage = "Letters Only.")]
public string LastName { get; set; }
[Display(Name = "Birthday")]
[Required(ErrorMessage = "This field required.")]
public DateTime Birthday { get; set; }
public DateTime DateCreated { get; set; }
[Display(Name = "Mobile Number")]
[Required(ErrorMessage = "This field required.")]
[RegularExpression(#"^[0-9]+$", ErrorMessage = "Numeric input only.")]
public string MobileNumber { get; set; }
[Display(Name = "Address")]
[Required(ErrorMessage = "This field required.")]
public string Address { get; set; }
public int UserIsDeleted { get; set; }
public int UserRoleId { get; set; }
public UserRole UserRole { get; set; }
}
}
And lastly, my method which adds the user to my database:
using ForumSite.ActionsAndMethods.Registration;
using ForumSite.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ForumSite.ActionsAndMethods
{
public class RegisterAction : IRegistration
{
ForumDBEntities ent = new ForumDBEntities();
public void Registration(IRegistration reg)
{
reg.DateCreated = DateTime.Now;
reg.UserRoleId = 1;
reg.UserIsDeleted = 0;
ent.Users.Add(reg);
ent.SaveChanges();
}
string IRegistration.Address { get; }
int IRegistration.UserId { get; }
string IRegistration.Email { get; }
string IRegistration.Password { get; }
string IRegistration.FirstName { get; }
string IRegistration.LastName { get; }
DateTime IRegistration.Birthday { get; }
DateTime IRegistration.DateCreated { get; set; }
string IRegistration.MobileNumber { get; }
int IRegistration.UserIsDeleted { get; set; }
int IRegistration.UserRoleId { get; set; }
UserRole IRegistration.UserRole { get; }
}
}
I wonder what causes this error?

While every User implements IRegistration, not every IRegistration instance is a User.
For example, your RegisterAction also implements IRegistration. So if what you wanted to do was possible, you could, in theory have this code:
RegisterAction action = GetRegisterAction();
RegisterAction action2 = new RegisterAction(action);
Which means when you come to do:
ent.Users.Add(reg);
It will fail because reg is not a User.
You could work around it like this:
var user = reg as User;
if(user != null)
{
ent.Users.Add(user);
}
But really you should probably take a look at your structure first as it seems quite odd to be doing this.

You have not told is exactly where you get the compile error but my guess is that it in the line ent.Users.Add(reg) in the Registration method.
To fix the compile error you should change the argument to the Registration method from IRegistration to User:
public void Registration(User reg)
{
reg.DateCreated = DateTime.Now;
reg.UserRoleId = 1;
reg.UserIsDeleted = 0;
ent.Users.Add(reg);
ent.SaveChanges();
}
However, this may trigger another compile error further up the call chain if you try to pass an IRegistration instead of a User to the Registration method.
While User can (and does) implement IRegistration you cannot assume that anything implementing IRegistration is an User. If your code is based on that assumption you will have to fix that to solve your problem.

Related

Not able to update table in asp.net using add parameters

I am trying to update table patient using the patientId in mysql from asp.net.By using the debugger I am able to see that the execute query for update is not getting executed. May be there is a problem with the syntax of add parameters for update.I will be extremely grateful if someone can find the solution for it.
The function in service class to update patient record:
public bool UpdatePatient(AppointmentInfo appointmentInfo)
{
bool set = false;
conn.GetConnection();
try
{
MySqlCommand cmd = conn.GetCommand(Queries.UpdatePatient);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#patientId", Convert.ToInt32(appointmentInfo.patientId));
cmd.Parameters.AddWithValue("#fName", Convert.ToString(appointmentInfo.fName));
cmd.Parameters.AddWithValue("#mName", Convert.ToString(appointmentInfo.mName));
cmd.Parameters.AddWithValue("#lName", Convert.ToString(appointmentInfo.lName));
cmd.Parameters.AddWithValue("#age", Convert.ToInt32(appointmentInfo.age));
cmd.Parameters.AddWithValue("#gender", Convert.ToString(appointmentInfo.gender));
cmd.Parameters.AddWithValue("#address", Convert.ToString(appointmentInfo.address));
cmd.Parameters.AddWithValue("#emailId", Convert.ToString(appointmentInfo.emailId));
if (cmd.ExecuteNonQuery()>0)
{
set = true;
}
else
{
set = false;
}
}
catch (MySqlException)
{
set = false;
}
conn.CloseConnection();
return set;
}
Here Queries is a .resx file where I am writing the update query.The query is
update patient set fName=#fName,mName=#mName,lName=#lName,
age=#age,gender=#gender,address=#address,emailId=#emailId,
where patientId=#patientId
Here is the model class appointmentInfo
public class AppointmentInfo
{
public int appointmentId { get; set;}
public int patientId { get; set; }
public string dName { get; set; }
[Required(ErrorMessage = "Please provide the first name")]
[StringLength(50, MinimumLength = 1, ErrorMessage = "First Name cannot be longer than 50 characters and less than 1 character")]
[RegularExpression(#"^[a-zA-Z]+$", ErrorMessage = "Use alphabets only please")]
public string fName { get; set; }
[RegularExpression(#"^[a-zA-Z]+$", ErrorMessage = "Use alphabets only please")]
public string mName { get; set; }
[Required(ErrorMessage = "Please provide the last name")]
[StringLength(50, MinimumLength = 1, ErrorMessage = "Last Name cannot be longer than 50 characters and less than 1 character")]
[RegularExpression(#"^[a-zA-Z]+$", ErrorMessage = "Use alphabets only please")]
public string lName { get; set; }
[Required]
[Range(1, 100, ErrorMessage = "Enter an age between 1 and 100")]
public int age { get; set; }
[Required(ErrorMessage = "Please provide the gender")]
public string gender { get; set; }
[Required(ErrorMessage = "Mobile Number is required")]
[RegularExpression(#"^(\d{10})$", ErrorMessage = "Please enter proper contact details.")]
public string phNo { get; set; }
[Required(ErrorMessage = "Please provide the address")]
[StringLength(50, MinimumLength = 10, ErrorMessage = "Address cannot be longer than 50 characters and less than 10 characters")]
public string address { get; set; }
[Required(ErrorMessage = "The email Id is required")]
[EmailAddress(ErrorMessage = "Invalid Email Address")]
public string emailId { get; set; }
[Required(ErrorMessage = "Please select an option")]
public int specialityId { get; set; }
public string specialityName { get; set; }
[Required(ErrorMessage = "Please select an option")]
public int doctorId { get; set; }
[Required(ErrorMessage = "Please provide the date and time")]
[DataType(DataType.DateTime)]
public DateTime dtTime { get; set; }
[NotMapped]
public List<SpecialityInfo> specialityCollection { get; set; }
[NotMapped]
public List<DoctorInfo> doctorCollection { get; set; }
}

How to not make information save to database-ASP.NET MVC

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.

Data Annotation Validation for a Group of Fields in Model

I am new to MVC 3 Data Annotations and I just want to ask that if its possible to add Validation on a Group of Fields in Model and Display the validation if none of it has Value?
this is the set of fields in my Data model
public class ContactModel
{
public Nullable<int> Id { get; set; }
[Display(Name = "Contact Firstname")]
[Required(ErrorMessage = "Required!")]
public string ContactFirstname { get; set; }
[Display(Name = "Contact Lastname")]
[Required(ErrorMessage = "Required!")]
public string ContactLastname { get; set; }
[Display(Name = "Contact Middlename")]
public string ContactMiddlename { get; set; }
[Display(Name = "Phone")]
[Required(ErrorMessage = "Required!")]
public string ContactPhone { get; set; }
[Display(Name = "Mobile ")]
[Required(ErrorMessage = "Required!")]
public string ContactMobile { get; set; }
[Display(Name = "Email")]
[Required(ErrorMessage = "Required!")]
public string ContactEmail { get; set; }
[Display(Name = "Job Title")]
[StringLength(50, ErrorMessage = "Max character reached!")]
public string ContactJobTitle { get; set; }
}
And I want to add validation if one from Phone,Mobile or Email doesn't have value
Thanks
You can implement IValidatableObject interface and add validation for all necessary properties:
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if(string.IsNullOrEmpty(Phone) || string.IsNullOrEmpty(Mobile) || string.IsNullOrEmpty(Email))
{
yield return new ValidationResult("Some error message");
}
}
Of course you should remove [Required] attributes then from those properties.

How to correctly use asp.net mvc database models?

The question I had was how are models supposed to be used? I don't think I am using them correctly. Whenever I make a change to the database (user table, in this case) and rebuild the model, my changes get erased and I end up making the changes again. The changes made are adding attributes and also another column(ConfirmPassword).
Edit: I am using EF 5
This is the model that was created by the database:
using System;
using System.Collections.Generic;
public partial class User
{
public User()
{
this.Documents = new HashSet<Document>();
}
public int UserId { get; set; }
public string Username { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public string Grade { get; set; }
}
With my changes:
using System;
using System.Collections.Generic;
using CompareObsolete = System.Web.Mvc.CompareAttribute;
public partial class User
{
public User()
{
this.Documents = new HashSet<Document>();
}
[Key]
public int UserId { get; set; }
[Required]
[StringLength(15, MinimumLength = 3)]
[Display(Name = "Username*: ")]
public string Username { get; set; }
[Required]
[EmailAddress]
[StringLength(25)]
[Display(Name = "Email Address*: ")]
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
[StringLength(50, MinimumLength = 4)]
[Display(Name = "Password*: ")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm Password*: ")]
[CompareObsolete("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
[Required]
[Display(Name = "Your Grade*: ")]
public string Grade { get; set; }
}
1. Create UserMetaData Class
public class UserMetaData
{
[Key]
public int UserId { get; set; }
[Required]
[StringLength(15, MinimumLength = 3)]
[Display(Name = "Username*: ")]
public string Username { get; set; }
[Required]
[EmailAddress]
[StringLength(25)]
[Display(Name = "Email Address*: ")]
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
[StringLength(50, MinimumLength = 4)]
[Display(Name = "Password*: ")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm Password*: ")]
[CompareObsolete("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
[Required]
[Display(Name = "Your Grade*: ")]
public string Grade { get; set; }
}
2. Create new partial class in new .cs file and assign metadata class to there by using MetadataType attribute to it.
[MetadataType(typeof(UserMetaData))] // assign type of your metadata here.
public partial class User
{
}

Confusing data annotation validation

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

Categories