在winform中验证控件(使用Devexpress)

时间:2012-09-06 10:32:57

标签: .net winforms validation devexpress

我在.NET和DevExpress第三方组件中使用WinForms。 如何验证表单中多个组件的数据并以自定义方式对其进行汇总?

1 个答案:

答案 0 :(得分:1)

试试这段代码:

using DevExpress.XtraEditors.DXErrorProvider;

// ...
ConditionValidationRule containsValidationRule = new ConditionValidationRule();
containsValidationRule.ConditionOperator = ConditionOperator.Contains;
containsValidationRule.Value1 = '@';
containsValidationRule.ErrorText = "Please enter a valid email";
containsValidationRule.ErrorType = ErrorType.Warning;

CompareAgainstControlValidationRule compValidationRule = 
    new CompareAgainstControlValidationRule();
compValidationRule.Control = notEmptyTextEdit;
compValidationRule.CompareControlOperator = CompareControlOperator.Equals;
compValidationRule.ErrorText = "Please enter a value that equals to the first editor's value";
compValidationRule.CaseSensitive = true;

CustomValidationRule customValidationRule = new CustomValidationRule();
customValidationRule.ErrorText = "Please enter a valid person name";
customValidationRule.ErrorType = ErrorType.Warning;

dxValidationProvider1.SetValidationRule(containsTextEdit, containsValidationRule);
dxValidationProvider1.SetValidationRule(compareTextEdit, compValidationRule);
dxValidationProvider1.SetValidationRule(customTextEdit, customValidationRule);

// Represents a custom validation rule.
public class CustomValidationRule : ValidationRule {
    public override bool Validate(Control control, object value) {
        string str = (string)value;
        string[] values = new string[] { "Dr.", "Mr.", "Mrs.", "Miss", "Ms." };
        bool res = false;
        foreach(string val in values) {
            if(ValidationHelper.Validate(str, ConditionOperator.BeginsWith, 
                val, null, null, false)) {
                string name = str.Substring(val.Length);
                if(name.Trim().Length > 0) res = true;
            }
        }
        return res;
    }
}

来源:http://documentation.devexpress.com/#WindowsForms/CustomDocument9481