繼承 BaseTextBox,針對數值型別 實作範圍驗證:
public abstract class NumberTextBox: BaseTextBox where T : IComparable { public virtual T MinValue { get; set; } = default(T); public virtual T MaxValue { get; set; } = default(T); protected abstract T DefaultMinValue { get; } protected abstract T DefaultMaxValue { get; } public virtual ValidationDataType Type { get; set; } public NumberTextBox() { this.FilterType = FilterTypes.Numbers; this.Options = TextBoxOptions.Required | TextBoxOptions.Filtered; this.MaxValue = this.DefaultMaxValue; this.MinValue = this.DefaultMinValue; } protected override void BuildValidatorControls() { base.BuildValidatorControls(); // 根據 Min/Max 是否異於預設值,動態添加 RangeValidator 或 CompareValidator if (MinValueChanged && MaxValueChanged) AddRangeValidator(); else if (MinValueChanged) AddMinCompareValidator(); else if (MaxValueChanged) AddMaxCompareValidator(); } // 驗證控件建立邏輯省略... }
public class IntNumberTextBox : NumberTextBox{ public IntNumberTextBox() { this.Type = ValidationDataType.Integer; } protected override int DefaultMinValue => int.MinValue; protected override int DefaultMaxValue => int.MaxValue; } public class MoneyTextBox : NumberTextBox { public MoneyTextBox() { this.Type = ValidationDataType.Currency; } protected override decimal DefaultMinValue => decimal.MinValue; protected override decimal DefaultMaxValue => decimal.MaxValue; }
where T : IComparable<T> 確保型別可比較。此模式將「輸入過濾、必填驗證、範圍驗證」封裝於控件內部,頁面使用極簡潔:<custom:MoneyTextBox MinValue="0" MaxValue="10000" />。