链接文本框控件的必填字段和正则表达式验证器的问题

本文关键字:正则表达式 验证 问题 字段 文本 控件 链接 | 更新日期: 2023-09-27 18:10:46

我正在尝试用ASP.net实现表单验证,我已经尝试了这里建议的每个解决方案,但到目前为止最好的一个是在aspsnippets.com上。

我的代码如下:

<asp:TextBox ID="tTitle" runat="server" onblur="WebForm_OnBlur()"/>
<asp:RequiredFieldValidator runat="server" ControlToValidate="tTitle"/>
<asp:TextBox ID="tEMail" runat="server" onblur="WebForm_OnBlur()"/>
<asp:RequiredFieldValidator runat="server" ControlToValidate="tEMail"/>
<asp:RegularExpressionValidator runat="server" ControlToValidate="tEMail"
ValidationExpression="'w+([-+.']'w+)*@'w+([-.]'w+)*'.'w+([-.]'w+)*"/>
<asp:LinkButton ID="btnSubmit" runat="server" Text="Submit"/>
Javascript

<script type="text/javascript">
function WebForm_OnSubmit() {
    if (typeof (ValidatorOnSubmit) == "function" && ValidatorOnSubmit() == false)
    {
        for (var i in Page_Validators) {
            try {
                var control =
                document.getElementById(Page_Validators[i].controltovalidate);
                if (!Page_Validators[i].isvalid) {
                    control.className = "error";
                } else {
                    control.className = "";
                }
            } catch (e) { }
        } return false;
    } return true;
}
function WebForm_OnBlur() {
    for (var i in Page_Validators) {
        try {
            var control =
            document.getElementById(Page_Validators[i].controltovalidate);
            if (!Page_Validators[i].isvalid) {
                control.className = "error";
            } else {
                control.className = "";
            }
        } catch (e) { }
    } return false;
}
</script>

问题是e-mail字段只验证正则表达式。如果我更改验证器的顺序,它只验证所需的表达式。

可能的问题是,代码循环遍历所有验证器,但不比较一次引用相同控件的验证器。这将导致只对控件应用最后一个验证器条件。

链接文本框控件的必填字段和正则表达式验证器的问题

可能的问题是,代码循环遍历所有验证器,但不比较一次引用相同控件的验证器。这将导致仅将最后一个验证器条件应用于控件。

是的,这确实是问题所在。要修复它,您可以执行以下操作:

WebForm_OnBlur函数中,循环遍历与失去焦点的控件相关的验证器(而不是页面上的所有验证器),并且仅当所有验证器都有效时才清除className属性:

function WebForm_OnBlur(control) {
    for (var i = 0; i < control.Validators.length; i++) {
        if (!control.Validators[i].isvalid) {
            control.className = "error";
            return;
        }
    }
    control.className = "";
}

TextBox控件的onblur属性中,将this作为参数传递给WebForm_OnBlur:

<asp:TextBox ID="tTitle" runat="server" onblur="WebForm_OnBlur(this)"/>
<asp:TextBox ID="tEMail" runat="server" onblur="WebForm_OnBlur(this)"/>

WebForm_OnSubmit函数中,为每个具有关联验证器的控件调用WebForm_OnBlur:

function WebForm_OnSubmit() {
    if (typeof(ValidatorOnSubmit) === "function" && ValidatorOnSubmit() === false) {
        for (var i = 0; i < Page_Validators.length; i++) {
            var control = document.getElementById(Page_Validators[i].controltovalidate);
            if (Page_Validators[i] === control.Validators[0]) // minor optimization
                WebForm_OnBlur(control);
        }
        return false;
    }
    return true;
}

除了@MichaelLiu,您还可以创建从CustomValidator类继承的自己的验证器,并更改验证器的呈现,使它们更容易使用。

例如:

Validators.cs


注意我们是如何添加CssControlErrorClass属性的。我们将在应用有问题的无效输入的类时使用它。

我们还设置了其他属性,所以你不必每次都设置它们,ClientValidationFunctionValidateEmptyText

public class RequiredFieldValidator : CustomValidator
{
    public string CssControlErrorClass { get; set; }
    public RequiredFieldValidator()
    {
        ClientValidationFunction = "validators.required";
        ValidateEmptyText = true;
    }
    public string InitialValue
    {
        get
        {
            object o = ViewState["InitialValue"];
            return ((o == null) ? String.Empty : (string)o);
        }
        set
        {
            ViewState["InitialValue"] = value;
        }
    }
    protected override void Render(HtmlTextWriter writer)
    {
        //Have to add attributes BEFORE the beginning tag is written to the stream
        writer.AddAttribute("data-errorClass", CssControlErrorClass);
        writer.AddAttribute("data-for", GetControlRenderID(ControlToValidate));
        base.Render(writer);
    }

    protected override bool EvaluateIsValid()
    {
        //Default implementation of the RequiredFieldValidation validator
        string controlValue = GetControlValidationValue(ControlToValidate);
        if (controlValue == null)
        {
            return true;
        }
        var result = (!controlValue.Trim().Equals(InitialValue.Trim()));
        //Check to see if validation failed, if it did, add the class to the control to validate
        if (!result)
        {
            var control = (WebControl) NamingContainer.FindControl(ControlToValidate);
            //Didn't look into it too much, but the validators fire twice for some reason
            if(!control.CssClass.Contains(CssControlErrorClass)) control.CssClass += " " + CssControlErrorClass;
        }
        return result;
    }
}

public class RegularExpressionValidator : CustomValidator
{
    public string CssControlErrorClass { get; set; }
    public string ValidationExpression
    {
        get
        {
            object o = ViewState["ValidationExpression"];
            return ((o == null) ? String.Empty : (string)o);
        }
        set
        {
            try
            {
                Regex.IsMatch(String.Empty, value);
            }
            catch (Exception e)
            {
                throw new HttpException(string.Format("{0} - {1}", "Validator_bad_regex", value), e);
            }
            ViewState["ValidationExpression"] = value;
        }
    }
    public RegularExpressionValidator()
    {
        ClientValidationFunction = "validators.regex";
    }
    protected override void Render(HtmlTextWriter writer)
    {
        //Have to add attributes BEFORE the beginning tag is written to the stream
        writer.AddAttribute("data-errorClass", CssControlErrorClass);
        writer.AddAttribute("data-regex", ValidationExpression);
        writer.AddAttribute("data-for", GetControlRenderID(ControlToValidate));
        base.Render(writer);
    }
    protected override bool EvaluateIsValid()
    {
        //Default implementation of the RegularExpressionFieldvalidator
        string controlValue = GetControlValidationValue(ControlToValidate);
        if (controlValue == null || controlValue.Trim().Length == 0)
        {
            return true;
        }
        try
        {
            Match m = Regex.Match(controlValue, ValidationExpression);
            var result = (m.Success && m.Index == 0 && m.Length == controlValue.Length);
            //Check to see if validation failed, if it did, add the class to the control to validate
            if (!result)
            {
                var control = (WebControl) NamingContainer.FindControl(ControlToValidate);
                //Didn't look into it too much, but the validators fire twice for some reason
                if (!control.CssClass.Contains(CssControlErrorClass)) control.CssClass += " " + CssControlErrorClass;
            }
            return result;
        }
        catch
        {
            return true;
        }
    }
}

Validators.js


由于在前面的类中我们预定义了javascript函数,我们可以添加一个简单的脚本,如:

var v = window.validators = window.validators || {
    errorControlAttributeName: "data-for",
    errorClassAttributeName: "data-errorClass",
    regexAttributeName: "data-regex",
    required: function(src, args) {
        var controlId = src.getAttribute(v.errorControlAttributeName),
            errorClass = src.getAttribute(v.errorClassAttributeName),
            input = document.getElementById(controlId);
        var isValid = (args.Value !== "");
        v._toggleInputErrorState(input, errorClass, isValid);
        args.IsValid = isValid;
        return;
    },
    regex: function(src, args) {
        var controlId = src.getAttribute(v.errorControlAttributeName),
            errorClass = src.getAttribute(v.errorClassAttributeName),
            regexString = src.getAttribute(v.regexAttributeName),
            input = document.getElementById(controlId),
            regex = new RegExp(regexString);
        var isValid = regex.test(args.Value);
        v._toggleInputErrorState(input, errorClass, isValid);
        args.IsValid = isValid;
        return;
    },    
    /************* Helper functions ***********/
    _toggleInputErrorState: function (inputEl, errorClass, isValid) {
        if (!isValid) {
            if (!v._hasClass(inputEl, errorClass)) {
                inputEl.className += " " + errorClass;
            }
        } else {
            if (v._hasClass(inputEl, errorClass)) {
                //Not the most performant, but is sure is easiest
                inputEl.className = inputEl.className.replace(" " + errorClass, "");
            }
        }
    },
    _hasClass: function(el, className) {
        return el.className.indexOf(className) != -1 ? true : false;
    },
}

非常简单的验证库,你可以很容易地扩展到你真正感兴趣的东西。

default . aspx


之后,您可以将控件放入页面:

<Validators:RequiredFieldValidator runat="server" CssControlErrorClass="input-validation-error" ControlToValidate="Test" ErrorMessage="REQUIRED BRO!"></Validators:RequiredFieldValidator>
<Validators:RegularExpressionValidator runat="server" ValidationExpression="[0-9]" CssControlErrorClass="input-validation-error" ControlToValidate="Test" ErrorMessage="REQUIRED RegEx BRO!"></Validators:RegularExpressionValidator>

这是最好的方法吗?可能不会,(这两个使用微软提供的默认实现)有很多比我更聪明的人,我也不怎么使用WebForms。我看到的最大好处是,你得到了一些可重用的代码,使用熟悉的语法,最终将包含所有的验证需求,而不是每次都用js来获得你想要的验证"规则"。

通过替换下面的代码片段来解决这个问题。为了纠正错误,我们必须循环遍历控件的所有验证器,然后决定是否必须用错误类标记它。在此之后,您的代码将按预期工作。

替换循环

 for (var i in Page_Validators) {
    try {
        var control =
        document.getElementById(Page_Validators[i].controltovalidate);
        if (!Page_Validators[i].isvalid) {
            control.className = "error";
        } else {
            control.className = "";
        }
    } catch (e) { }
}

,代码为

 for (var j in Page_Validators) {
        try {
            var control =
                        document.getElementById(Page_Validators[j].controltovalidate);
            var IsError = false;
            for (var i in control.Validators) {
                if (!control.Validators[i].isvalid) {
                    IsError = true;
                }
            }
            if (IsError)
                control.className = "error";
            else
                control.className = "";
        } catch (e) { }
    }

我刚刚运行它,这是工作得很好:)试试这个解决方案!

你可以尝试在javascript中使用Page_ClientValidate()而不是遍历验证器。我相信这将验证页面上的所有验证器。如果您想验证由特定验证组绑定的特定控件,它还接受"验证组名称"参数。