简体   繁体   English

Asp MVC 2针对现有电子邮件地址的远程验证,但是如何编辑?

[英]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. 我正在使用ASP MVC 2和远程验证。 I have a model called PersonVM, which AddPersonVM and EditPersonVM inherit from. 我有一个名为PersonVM的模型,AddPersonVM和EditPersonVM继承自该模型。 This is so I can use one usercontrol to handle most of the UI that is the same between both subclassed models. 因此,我可以使用一个用户控件来处理两个子类化模型之间相同的大部分UI。

 /// <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. 我有2个从该模型继承的模型AddPersonVM和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. [UniqueEmailAddress]是我的RemoteAttribute,用于检查现有的电子邮件地址以及出现的问题。

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. 我想做的是存储属性值的原始值,并将其从IsValid检查的内容中​​排除。

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. 到目前为止,我可以将EmailAddress属性分别添加到AddPersonVM和EditPersonVM,从我的usercontrol视图中删除该字段并添加到这两个视图中,并删除Edit上的属性,但是那样一来,任何人都无法编辑其帐户他们想要的任何电子邮件地址。 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). 因此,我的建议是向IsEmailAddressInUse添加另一个属性(字符串电子邮件,布尔IsEdit)。 If IsEdit is true then check email address from user loggedin info. 如果IsEdit为true,则从用户登录信息中检查电子邮件地址。 If same return true if not check uniquness. 如果相同,则返回true,否则不检查唯一性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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