简体   繁体   中英

Asp MVC 2 Remote Validation Against Existing Email Address, but What About Editing?

Long-time reader, first time poster.

I'm using ASP MVC 2 and remote validation. I have a model called PersonVM, which AddPersonVM and EditPersonVM inherit from. This is so I can use one usercontrol to handle most of the UI that is the same between both subclassed models.

 /// <summary> /// This class handles adding and editing people. /// </summary> [MustHaveAtLeastOneOf("HomePhoneNumber", "CellPhoneNumber", ErrorMessage="At least one of the phone numbers must be filled in.")] public abstract class PersonVM : WebViewModel { #region Reference (for Binding) /// <summary> /// Provides a list of person types, eg Teacher, Student, Parent. /// </summary> public IEnumerable<PersonType> ListOfPersonTypes { get { if (_listOfPersonTypes == null) { _listOfPersonTypes = Data.PersonTypes .Where(pt => pt.OrganizationID == ThisOrganization.ID || pt.OrganizationID == null) .OrderBy(pt => pt.Name).ToArray(); } return _listOfPersonTypes; } } private IEnumerable<PersonType> _listOfPersonTypes = null; /// <summary> /// Provides a list of schools the person can belong to. /// </summary> public IEnumerable<School> ListOfSchools { get { if (_listOfSchools == null) { _listOfSchools = Data.Schools .Where(s => (s.OrganizationID == ThisOrganization.ID || s.OrganizationID == null) // TODO && s.Deleted == false ) .OrderBy(s => s.Name); } return _listOfSchools; } } private IEnumerable<School> _listOfSchools = null; /// <summary> /// Provides a list of contact types, eg Home phone, email. /// </summary> public IEnumerable<ContactType> ListOfContactTypes { get { if (_listOfContactTypes == null) { _listOfContactTypes = Data.ContactTypes .OrderBy(ct => ct.Name); } return _listOfContactTypes; } } private IEnumerable<ContactType> _listOfContactTypes = null; /// <summary> /// Provides a list of genders. /// </summary> public IEnumerable<string> Genders { get { return new string[] { null, "Male", "Female" }; } } /// <summary> /// Returns a list of US states. /// </summary> public List<StaticData.USState> ListOfUSStates { get { return StaticData.USStates; } } #endregion /// <summary> /// Represents the current person being edited. /// </summary> public Person CurrentPerson { get; set; } #region Abstracted Required Fields /* * This is done, since address information, DOB * are not required on the panel, but are required fields here. * I tried implementing an interface called IPersonAddressRequired * with this information in it, but it didn't work. Additionally, * only one instance of [MetadataType] is allowed on a class, * so that didn't work either. */ [Required] [StringLength(100)] public string Address { get { return CurrentPerson.Address; } set { CurrentPerson.Address = value; } } [StringLength(100)] public string Address2 { get { return CurrentPerson.Address2; } set { CurrentPerson.Address2 = value; } } [Required] [StringLength(50)] public string City { get { return CurrentPerson.City; } set { CurrentPerson.City = value; } } [Required] [StringLength(50)] public string State { get { return CurrentPerson.State; } set { CurrentPerson.State = value; } } [Required] [StringLength(50)] public string Zip { get { return CurrentPerson.Zip; } set { CurrentPerson.Zip = value; } } [DataType(DataType.Date)] [Required] public DateTime? DOB { get { return CurrentPerson.DOB; } set { CurrentPerson.DOB = value; } } [Required] public string Gender { get { return CurrentPerson.Gender; } set { CurrentPerson.Gender = value; } } #endregion #region Abstracted Contact Methods /// <summary> /// When adding someone, this represents the phone number contact record. /// </summary> [Display(Name = "Home Phone Number")] [DisplayName("Home Phone Number")] [USPhoneNumber] //[Required] public string HomePhoneNumber { get; set; } /// <summary> /// When adding someone, this represents the phone number contact record. /// </summary> [Display(Name = "Cell Phone Number")] [DisplayName("Cell Phone Number")] [USPhoneNumber] //[Required] public string CellPhoneNumber { get; set; } /// <summary> /// When adding someone, this represents the email address contact record. /// </summary> [Display(Name = "Email Address")] [DisplayName("Email Address")] [Required] [UniqueEmailAddress(ErrorMessage="The email address was already found in our system, please sign in or use another email.")] [Email(ErrorMessage="The email address specified isn't an email address.")] public string EmailAddress { get; set; } #endregion ////////////////////////////// /// <summary> /// Sets the picture to be uploaded. /// </summary> public byte[] PictureData { get; set; } /// <summary> /// One of 'keep', 'remove', 'replace'. /// </summary> public string PictureAction { get; set; } } 

I have 2 models that inherit from this model, AddPersonVM and EditPersonVM. Each implements how they handle submitting changes a little differently.

[UniqueEmailAddress] is my RemoteAttribute that checks for an existing email address, and what I have issue with.

This works fine on adding someone, but when editing an existing person, the email address already stored exists in the membership system, so it fails validation. What I would like to do is store the original value of the property's value, and exclude that from what IsValid checks.

My code:

 /// <summary> /// Checks to be sure that an entered email address is unique. /// </summary> public class UniqueEmailAddressAttribute : RemoteAttribute { /// <summary> /// Returns true if the email address specified is currently in use. /// </summary> /// <param name="emailAddress"></param> /// <returns></returns> public static bool IsEmailAddressInUse(string emailAddress) { return (Membership.FindUsersByEmail(emailAddress).Count != 0); } /////////////////////////// public UniqueEmailAddressAttribute() : base("UniqueEmailAddress", "RemoteValidation", "emailAddress") { } /////////////////////////// public override bool IsValid(object value) { // If value is null, return true, since a [Required] attribute handles required values. if (value == null) return true; // Value must be a string. if (!(value is string)) return false; // We're not checking the validity of the email address here, // the [EmailAddress] attribute handles that for us. // Check the email's uniqueness. return !IsEmailAddressInUse((string)value); } } 

What I would like to have:

/// /// Checks to be sure that an entered email address is unique. /// public class UniqueEmailAddressAttribute : RemoteAttribute {

string OriginalValue = null; /// <summary> /// Returns true if the email address specified is currently in use. /// </summary> /// <param name="emailAddress"></param> /// <returns></returns> public static bool IsEmailAddressInUse(string emailAddress) { return (Membership.FindUsersByEmail(emailAddress).Count != 0); } /////////////////////////// public UniqueEmailAddressAttribute() : base("UniqueEmailAddress", "RemoteValidation", "emailAddress") { OriginalValue = value Found using reflection or something; } /////////////////////////// public override bool IsValid(object value) { // If value is null, return true, since a [Required] attribute handles required values. if (value == null) return true; // Value must be a string. if (!(value is string)) return false; // We're not checking the validity of the email address here, // the [EmailAddress] attribute handles that for us. if ((string)value == OriginalValue) return true; // Check the email's uniqueness. return !IsEmailAddressInUse((string)value); } }

 string OriginalValue = null;  /// <summary> /// Returns true if the email address specified is currently in use. /// </summary> /// <param name="emailAddress"></param> /// <returns></returns> public static bool IsEmailAddressInUse(string emailAddress) { return (Membership.FindUsersByEmail(emailAddress).Count != 0); } /////////////////////////// public UniqueEmailAddressAttribute() : base("UniqueEmailAddress", "RemoteValidation", "emailAddress") { OriginalValue = value Found using reflection or something; } /////////////////////////// public override bool IsValid(object value) { // If value is null, return true, since a [Required] attribute handles required values. if (value == null) return true; // Value must be a string. if (!(value is string)) return false; // We're not checking the validity of the email address here, // the [EmailAddress] attribute handles that for us. if ((string)value == OriginalValue) return true; // Check the email's uniqueness. return !IsEmailAddressInUse((string)value); } } 

Any ideas? As of now, I could add the EmailAddress property individually to both AddPersonVM and EditPersonVM, take the field out of my usercontrol view and add to both views, and remove the attribute on Edit, but then that would stop noone from editing their account to have whatever email address they want. I don't care if reflection is required to read the original value, that's cool.

Thanks in advance! - Derreck

I think you want to add person with unique email address and if any user try to change his/her email address which is in use you want to check uniquness if he change, but you also don't want to check uniquness if he does not change his email address.

So my suggestion is add one more property to IsEmailAddressInUse (string email, bool IsEdit). If IsEdit is true then check email address from user loggedin info. If same return true if not check uniquness.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM