English 中文(简体)
比较数据。 页: 1
原标题:Compare Dates DataAnnotations Validation asp.net mvc

请允许我说,除了起步日期之外,如果最终批准的期限不超过3个月,我就想检查。

public class DateCompare : ValidationAttribute 
 {
    public String StartDate { get; set; }
    public String EndDate { get; set; }

    //Constructor to take in the property names that are supposed to be checked
    public DateCompare(String startDate, String endDate)
    {
        StartDate = startDate;
        EndDate = endDate;
    }

    public override bool IsValid(object value)
    {
        var str = value.ToString();
        if (string.IsNullOrEmpty(str))
            return true;

        DateTime theEndDate = DateTime.ParseExact(EndDate, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
        DateTime theStartDate = DateTime.ParseExact(StartDate, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture).AddMonths(3);
        return (DateTime.Compare(theStartDate, theEndDate) > 0);
    }
}

我愿在我的验证中落实这一点。

[DateCompare(“StartDate”),“EndDate”, ErrorMessage = “The Deal can only be 3个月 long.”

我知道我这里有了一个错误......但我如何能够在网上验证这种业务规则。

问题回答

答案很晚,但我要向其他方面表示。 这里,我是如何这样做的,以便利用不真实的客户验证来验证所有东西:

  1. 创建归属类别:

    public class DateCompareValidationAttribute : ValidationAttribute, IClientValidatable
    {
    
      public enum CompareType
      {
          GreatherThen,
          GreatherThenOrEqualTo,
          EqualTo,
          LessThenOrEqualTo,
          LessThen
      }
    
    
    
    
      private CompareType _compareType;
      private DateTime _fromDate;
      private DateTime _toDate;
    
      private string _propertyNameToCompare;
    
      public DateCompareValidationAttribute(CompareType compareType, string message, string compareWith = "")
    {
        _compareType = compareType;
        _propertyNameToCompare = compareWith;
        ErrorMessage = message;
    }
    
    
    #region IClientValidatable Members
    /// <summary>
    /// Generates client validation rules
    /// </summary>
    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        ValidateAndGetCompareToProperty(metadata.ContainerType);
        var rule = new ModelClientValidationRule();
    
        rule.ErrorMessage = ErrorMessage;
        rule.ValidationParameters.Add("comparetodate", _propertyNameToCompare);
        rule.ValidationParameters.Add("comparetype", _compareType);
        rule.ValidationType = "compare";
    
        yield return rule;
    }
    
    #endregion
    
    
     protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
         // Have to override IsValid method. If you have any logic for server site validation, put it here. 
        return ValidationResult.Success;
    
    }
    
    /// <summary>
    /// verifies that the compare-to property exists and of the right types and returnes this property
    /// </summary>
    /// <param name="containerType">Type of the container object</param>
    /// <returns></returns>
    private PropertyInfo ValidateAndGetCompareToProperty(Type containerType)
    {
        var compareToProperty = containerType.GetProperty(_propertyNameToCompare);
        if (compareToProperty == null)
        {
            string msg = string.Format("Invalid design time usage of {0}. Property {1} is not found in the {2}", this.GetType().FullName, _propertyNameToCompare, containerType.FullName);
            throw new ArgumentException(msg);
        }
        if (compareToProperty.PropertyType != typeof(DateTime) && compareToProperty.PropertyType != typeof(DateTime?))
        {
            string msg = string.Format("Invalid design time usage of {0}. The type of property {1} of the {2} is not DateType", this.GetType().FullName, _propertyNameToCompare, containerType.FullName);
            throw new ArgumentException(msg);
        }
    
        return compareToProperty;
    }
    }
    

    说明:如果你想要确定时间长度,就这一特定类型的比较而言,将另外增加一个参数:

  2. 将实地的属性改为:
    。 相比之下,“这一日期必须是另一日期或之后的”,比较“另一日期”:

  3. 注意如何改变你产生的html。 它应包括你的验证信息、比较日期的实地名称等。 生成的区块将首先使用“数据-比较”。 当你在GetClientValidation Ruless方法中确定“ValidationType=“compare”时,你将这一“compare”定义为。

  4. 现在,你们需要配对“javascript”代码:增加验证适应器和验证方法。 我在这里使用了臭名昭著的方法,但你没有。 我建议将这一法典放在单独的javascript档案中,以便与你的属性阶层一道成为一种控制,并且可以在任何地方使用。 www.un.org/Depts/DGACM/index_spanish.htm

$.validator.unobtrusive.adapters.add( compare , [ comparetodate , comparetype ], function (options) { options.rules[ compare ] = options.params; options.messages[ compare ] = options.message; } );

$.validator.addMethod("compare", function (value, element, parameters) {
    // value is the actuall value entered 
    // element is the field itself, that contain the the value (in case the value is not enough)

    var errMsg = "";
    // validate parameters to make sure everyting the usage is right
    if (parameters.comparetodate == undefined) {
        errMsg = "Compare validation cannot be executed: comparetodate parameter not found";
        alert(errMsg);
        return false;
    }
    if (parameters.comparetype == undefined) {
        errMsg = "Compare validation cannot be executed: comparetype parameter not found";
        alert(errMsg);
        return false;
    }


    var compareToDateElement = $( #  + parameters.comparetodate).get();
    if (compareToDateElement.length == 0) {
        errMsg = "Compare validation cannot be executed: Element to compare " + parameters.comparetodate + " not found";
        alert(errMsg);
        return false;
    }
    if (compareToDateElement.length > 1) {
        errMsg = "Compare validation cannot be executed: more then one Element to compare with id " + parameters.comparetodate + " found";
        alert(errMsg);
        return false;
    }
    //debugger;

    if (value && !isNaN(Date.parse(value))) {
        //validate only the value contains a valid date. For invalid dates and blanks non-custom validation should be used    
        //get date to compare
        var compareToDateValue = $( #  + parameters.comparetodate).val();
        if (compareToDateValue && !isNaN(Date.parse(compareToDateValue))) {
            //if date to compare is not a valid date, don t validate this
            switch (parameters.comparetype) {
                case  GreatherThen :
                    return new Date(value) > new Date(compareToDateValue);
                case  GreatherThenOrEqualTo :
                    return new Date(value) >= new Date(compareToDateValue);
                case  EqualTo :
                    return new Date(value) == new Date(compareToDateValue);
                case  LessThenOrEqualTo :
                    return new Date(value) <= new Date(compareToDateValue);
                case  LessThen :
                    return new Date(value) < new Date(compareToDateValue);
                default:
                    {
                        errMsg = "Compare validation cannot be executed:  " + parameters.comparetype + "  is invalid for comparetype parameter";
                        alert(errMsg);
                        return false;
                    }
            }
            return true;
        }
        else
            return true;

    }
    else
        return true;
});

这只涉及客户方的不侵犯性鉴定。 如果你需要服务器,那么你就不得不在超重的瓦利德方法中有一些逻辑。 此外,你可以利用反思,利用显示的属性生成错误信息,使电文成为选择性的。

  1. Dates

实体:

[MetadataType(typeof(MyEntity_Validation))]
public partial class MyEntity
{
}
public class MyEntity_Validation
{
    [Required(ErrorMessage=" Date from  is required")]
    public DateTime DateFrom { get; set; }

    [CompareDatesValidatorAttribute("DateFrom")]  
    public DateTime DateTo { get; set; }
}

受益方:

 public sealed class CompareDatesValidatorAttribute : ValidationAttribute
{
    private string _dateToCompare;  
    private const string _errorMessage = " {0}  must be greater or equal {1} ";  

    public CompareDatesValidatorAttribute(string dateToCompare)
        : base(_errorMessage)
    {
        _dateToCompare = dateToCompare;
    }

    public override string FormatErrorMessage(string name)
    {
        return string.Format(_errorMessage, name, _dateToCompare);
    } 

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var dateToCompare = validationContext.ObjectType.GetProperty(_dateToCompare);
        var dateToCompareValue = dateToCompare.GetValue(validationContext.ObjectInstance, null);
        if (dateToCompareValue != null && value != null && (DateTime)value < (DateTime)dateToCompareValue) 
        {
            return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
        }
        return null;
    }
}

2. 密码

实体:

   public string Password { get; set; }

    [Compare("Password", ErrorMessage = "ConfirmPassword must match Password")]
    public string ConfirmPassword { get; set; }

我希望它能提供帮助。

我只想到如何在班级而不是在财产一级这样做。 如果你创立了一个MVC应用程序,账户模式显示以下做法。

<>Class>:

  [PropertiesMustMatch("Password",
            "ConfirmPassword", ErrorMessage =
            "Password and confirmation password
            do not match.")]
                public class RegisterModel
                {

                    [Required(ErrorMessage = "Required")]
                    [DataType(DataType.EmailAddress)]
                    [DisplayName("Your Email")]
                    public string Email { get; set; }              

                    [Required(ErrorMessage = "Required")]
                    [ValidatePasswordLength]
                    [DataType(DataType.Password)]
                    [DisplayName("Password")]
                    public string Password { get; set; }

                    [Required(ErrorMessage = "Required")]
                    [DataType(DataType.Password)]
                    [DisplayName("Re-enter password")]
                    public string ConfirmPassword { get; set; }                
                }

www.un.org/Depts/DGACM/index_french.htm

[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
    public sealed class PropertiesMustMatchAttribute : ValidationAttribute
    {
        private const string _defaultErrorMessage = " {0}  and  {1}  do not match.";

        private readonly object _typeId = new object();

        public PropertiesMustMatchAttribute(string originalProperty, string confirmProperty)
            : base(_defaultErrorMessage)
        {
            OriginalProperty = originalProperty;
            ConfirmProperty = confirmProperty;
        }

        public string ConfirmProperty
        {
            get;
            private set;
        }

        public string OriginalProperty
        {
            get;
            private set;
        }

        public override object TypeId
        {
            get
            {
                return _typeId;
            }
        }

        public override string FormatErrorMessage(string name)
        {
            return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString,
                OriginalProperty, ConfirmProperty);
        }

        public override bool IsValid(object value)
        {
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(value);
            object originalValue = properties.Find(OriginalProperty, true /* ignoreCase */).GetValue(value);
            object confirmValue = properties.Find(ConfirmProperty, true /* ignoreCase */).GetValue(value);
            return Object.Equals(originalValue, confirmValue);
        }
}

附录

public class CompareValidatorAttribute : ValidationAttribute, IInstanceValidationAttribute
{
    public CompareValidatorAttribute(string prefix, string propertyName) {
        Check.CheckNullArgument("propertyName", propertyName);

        this.propertyName = propertyName;
        this.prefix = prefix;
    }

    string propertyName, prefix;

    public string PropertyName
    {
        get { return propertyName; }
    }

    public string Prefix
    {
        get { return prefix; }
    }

    #region IInstanceValidationAttribute Members

    public bool IsValid(object instance, object value)
    {
        var property = instance.GetType().GetProperty(propertyName);

        var targetValue = property.GetValue(instance, null);
        if ((targetValue == null && value == null) || (targetValue != null && targetValue.Equals(value)))
            return true;

        return false;
    }

    #endregion

    public override bool IsValid(object value)
    {
        throw new NotImplementedException();
    }
}

接口

public interface IInstanceValidationAttribute
{
    bool IsValid(object instance, object value);
}

鉴定人

public class CompareValidator : DataAnnotationsModelValidator<CompareValidatorAttribute>
{
    public CompareValidator(ModelMetadata metadata, ControllerContext context, CompareValidatorAttribute attribute)
        : base(metadata, context, attribute)
    {
    }

    public override IEnumerable<ModelValidationResult> Validate(object container)
    {
        if (!(Attribute as IInstanceValidationAttribute).IsValid(container, Metadata.Model))
            yield return (new ModelValidationResult
            {
                MemberName = Metadata.PropertyName,
                Message = Attribute.ErrorMessage
            });
    }

    public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
    {
        var rule = new ModelClientValidationRule() { ErrorMessage = Attribute.ErrorMessage, ValidationType = "equalTo" };
        rule.ValidationParameters.Add("equalTo", "#" + (!string.IsNullOrEmpty(Attribute.Prefix) ? Attribute.Prefix + "_" : string.Empty)+ Attribute.PropertyName);

        return new[] { rule };
    }
}

登记:

DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(CompareValidatorAttribute), typeof(CompareValidator));

感谢胎儿。 当我想把验证信息与财产联系起来时,我就把我的头脑rat。 如果您改过这条线,

[AttributeUsage(AttributeTargets.Class)]

......

[AttributeUsage(AttributeTargets.Property)]

您可以将上述一种特定财产作比较。 亲爱! 由于我的客户仍在3.5个间谍上工作,我们提供了很多帮助。 sad face





相关问题
Mysql compaire two dates from datetime?

I was try to measure what is faster and what should be the best way to compare two dates, from datetime record in MySql db. There are several approaches how to grab a date from date time, but I was ...

iPhone Date Picker rolls over to 2010 on December 27th?

So I implemented a UIDatepicker in one of my applications for scheduling and autodialing teleconferences... everything is pretty much ready to go except, while testing I noticed that when the date ...

Convert date Python

I have MMDDYY dates, i.e. today is 111609 How do I convert this to 11/16/2009, in Python?

specifying date format when using $form->inputs() in CakePHP

I am wondering if there is a way to specify the date format in the forms created using CakePHP s $form->inputs(); Please note that this is not the individual $form->input() but instead $form->inputs() ...

NSDateFormat, super simple! Where am I screwing up?

Ok, this is really simple, maybe I m a getting a bit burnt out, but seems like it should work, Query XML feed, put out date string, format, display in a cell. The issue is I m a getting a NULL ...

sqlite writing a date into an email

I am exporting a date value from sqlite and placing it into an email. The date appears like this 279498721.322872 I am using Objective C in an Iphone App. Does anyone know how to make this export ...

热门标签