且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在MVC中进行文本框验证(比较文本框值)?

更新时间:2022-12-20 12:06:31

您需要使用javascript或jquery进行客户端验证。下面是一个滑块示例: Asp.Net MVC 5 with Jquery滑块| ASP.NET论坛 [ ^ ]这里是一个jquery双范围滑块: jQRangeSlider:范围滑块的jQuery插件 [ ^ ]



从上面的链接创建工作解决方案应该不难。
You need to do client-side validation using javascript or jquery. Here is an example with a slider: Asp.Net MVC 5 with Jquery slider | The ASP.NET Forums[^] and here is a jquery dual range slider: jQRangeSlider: jQuery plugin for range sliders[^]

It should not be difficult to create a working solution from the above links.


我找到了解决方案,在这里我创建了我的自定义属性,[GreaterThan]

I found out the solution, Here i created my custom attribute, [GreaterThan]
[Required(ErrorMessage = "Signal Start Range Field Is Mandatory.")]  
        [DisplayName("Signal Start Range")]
        public string SignalStartRange { get; set; }

[Required(ErrorMessage = "Signal End Range Field Is Mandatory.")]
        [DisplayName("Signal End Range")]
        [GreaterThan(PropName = "SignalStartRange", ErrorMessage ="End rand should not be lesser than start ragne")]
        public string SignalEndRange { get; set; }



public class GreaterThanAttribute: ValidationAttribute
    {
        public string PropName { get; set; }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            PropertyInfo otherPropertyInfo = validationContext.ObjectType.GetProperty(PropName);

            var otherPropertyStringValue = otherPropertyInfo.GetValue(validationContext.ObjectInstance, null).ToString();

            if(Convert.ToUInt32(value) < Convert.ToUInt32(otherPropertyStringValue))
            {
                return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
            }
            return null;
        }
    }