具有互斥的自定义数据注释不会验证空字段

时间:2013-06-27 05:51:22

标签: jquery asp.net-mvc-4 data-annotations

我正在使用Visual Studio 2010在ASP.Net MVC4中开展一个项目。我需要实现自定义数据注释。我的要求如下:

1)IP地址和主机名有两个字段。用户可以输入其中任何一个。但不是两个

2)需要相应验证,当用户输入其中一个时,需要自动清除其他一个。

3)我还需要验证两者都不应该为空

根据上述要求,我提出了两个自定义属性,如下所示

[AttributeUsage(AttributeTargets.Property, AllowMultiple = true, Inherited = false)]
    public class IPAddressAttribute : ValidationAttribute, IClientValidatable
    {

        #region Propertie(s)
        /// <summary>
        /// Other dependent properties for validation
        /// </summary>
        public string CommaSeperatedProperties
        {
            get;
            private set;
        }
        #endregion

        #region Constructor(s)
        /// <summary>
        /// Parameterized constructor
        /// </summary>
        /// <param name="otherProperties">Other properties required for validation</param>
        public IPAddressAttribute(string otherProperties): base(defaultErrorMessage)
        {
            if (!string.IsNullOrWhiteSpace(otherProperties))
            {
                this.CommaSeperatedProperties = otherProperties;
            }
        }
        #endregion

        #region Public Method(s)

        public IEnumerable<ModelClientValidationRule>
                    GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            return new[] { new IPAddressValidationRule
            (FormatErrorMessage(metadata.DisplayName),
            CommaSeperatedProperties.Split(new char[]{','})) };
        }
        #endregion

        #region Protected Method(s)
        protected override ValidationResult IsValid(object value,
                    ValidationContext validationContext)
        {
           // Validation logic goes here
        }
        #endregion

        #region Field(s)
        private const string defaultErrorMessage = "{0} is invalid";
        #endregion
    }

/// <summary>
    /// Implements a custom validation attribute for Host name
    /// </summary>
    public class HostNameAttribute : ValidationAttribute, IClientValidatable
    {

        #region Propertie(s)
        /// <summary>
        /// Other dependent properties for validation
        /// </summary>
        public string CommaSeperatedProperties
        {
            get;
            private set;
        }
        #endregion

        #region Constructor(s)
        /// <summary>
        /// Parameterized constructor
        /// </summary>
        /// <param name="otherProperties">Other properties required for validation</param>
        public HostNameAttribute(string otherProperties) : base(defaultErrorMessage)
        {
            if (!string.IsNullOrWhiteSpace(otherProperties))
            {
                this.CommaSeperatedProperties = otherProperties;
            }
        }
        #endregion

        #region Public Method(s)

        public IEnumerable<ModelClientValidationRule>
                    GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            return new[] { new HostNameValidationRule
            (FormatErrorMessage(metadata.DisplayName), 
            CommaSeperatedProperties.Split(new char[]{','})) };
        }
        #endregion

        #region Protected Method(s)

        protected override ValidationResult IsValid(object value,
                    ValidationContext validationContext)
        {
            // Validation goes here
        }
        #endregion

        #region Field(s)
        private const string defaultErrorMessage = "{0} is invalid";
        #endregion
    }

我的javascript就像下面的

// Register method for the client side validation of IP Address
$.validator.unobtrusive.adapters.add("ipaddress", ['id', 'hostname'],
function (options) {
    var params = {
        id: options.params.id,
        hostname: options.params.hostname
    };
    options.rules['ipaddress'] = params;
    options.messages['ipaddress'] = options.message;
});

// Register method for the client side validation of Host name
jQuery.validator.unobtrusive.adapters.add("hostname", ['id', 'ipaddress'],
function (options) {
    var params = {
        id: options.params.id,
        ipaddress: options.params.ipaddress
    };
    options.rules['hostname'] = params;
    options.messages['hostname'] = options.message;
});


// jquery validate function to validate an IP address
$.validator.addMethod("ipaddress", function (value, element, params) {
    var result = true;
    if (value != "") {
        result = validateIPAddress(value);
        // Clear the host name field, since they are mutually exclusive
        var tempInd = element.id.search("IPAddress");
        var hostNameCtrlID = element.id.substring(0, tempInd) + params.hostname;
        if ($("#" + hostNameCtrlID).val() != "") {
            $("#" + hostNameCtrlID).val("");
            // trigger the validation in Host name field
            //$("#remDevForm").valid();
            if (result) {
                result = $("#myForm").validate().element($("#" + hostNameCtrlID));
            }
        }
    }
    else {
        // if both are empty, return false
        var tempInd = element.id.search("IPAddress");
        var hostNameCtrlID = element.id.substring(0, tempInd) + params.hostname;
        if ($("#" + hostNameCtrlID).val() == "") {
            result = false;
            $.validator.messages.ipaddress = "Please enter either Hostname or IP Address";
        }
    }
    return result;
}
);

// jquery validate function to validate Host name
$.validator.addMethod("hostname", function (value, element, params) {
    var result = true;
    if (value != "") {
        var result = validateHostName(value);
        // Clear the IP Address field, since they are mutually exclusive
        var tempInd = element.id.search("HostName");
        var ipAddressCtrlID = element.id.substring(0, tempInd) + params.ipaddress;
        if ($("#" + ipAddressCtrlID).val() != "") {
            $("#" + ipAddressCtrlID).val("");
            // trigger the validation in IP Address field
            //$("#myForm").valid();
            if (result) {
                result = $("#myForm").validate().element($("#" + ipAddressCtrlID));
            }
        }
    }
    else {
        // if both are empty, return false
        var tempInd = element.id.search("HostName");
        var ipAddressCtrlID = element.id.substring(0, tempInd) + params.ipaddress;
        if ($("#" + ipAddressCtrlID).val() == "") {
            result = false;
            $.validator.messages.hostname = "Please enter either Hostname or IP Address";
        }
    }
    return result;
});

验证效果很好

我在客户端验证方面面临以下问题。

1)当字段变空时不会触发验证。这是一个错误吗?请注意,我不能使用必需的,因为只有它们是强制性的。如果我输入一些值,则触发

2)无法获取我在java脚本中输入的自定义消息。而不是这个,我总是收到默认错误消息。

我知道这是一个冗长的代码而且对此抱歉。任何人都可以评论可能发生的错误吗?

0 个答案:

没有答案