使用必填字段验证器更改文本框颜色。 请不要使用扩展器控制

发布于 2024-07-06 09:55:40 字数 41 浏览 7 评论 0 原文

每当单击“提交”按钮时触发所需的字段验证器时,我需要更改文本框的颜色

I need to change color of TextBox whenever its required field validator is fired on Clicking the Submit button

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(17

南薇 2024-07-13 09:55:41

您可以做的是注册一个 Javascript 函数,该函数将在提交后遍历全局 Page_Validators 数组,并且您可以适当地设置背景。 这样做的好处是您可以在页面上的所有控件上使用它。 该函数如下所示:

function fnOnUpdateValidators()
{
   for (var i = 0; i < Page_Validators.length; i++)
   {
      var val = Page_Validators[i];
      var ctrl = document.getElementById(val.controltovalidate);
      if (ctrl != null && ctrl.style != null)
      {
         if (!val.isvalid)
            ctrl.style.background = '#FFAAAA';
         else
            ctrl.style.backgroundColor = '';
      }
   }
}

最后一步是使用 OnSubmit 事件注册脚本:

VB.NET:C#

Page.ClientScript.RegisterOnSubmitStatement(Me.GetType, "val", "fnOnUpdateValidators();")

Page.ClientScript.RegisterOnSubmitStatement(this.GetType(), "val", "fnOnUpdateValidators();");

您将在所有后面的代码中维护正确的 IsValid 状态,并且它可以与您的所有控件一起使用。

注意:我从 以下博客。 我只是想在这里记录一下,以防源博客出现故障。

What you can do is register a Javascript function that will iterate through the global Page_Validators array after submission and you can set the background appropriately. The nice thing about this is that you can use it on all of your controls on the page. The function looks like this:

function fnOnUpdateValidators()
{
   for (var i = 0; i < Page_Validators.length; i++)
   {
      var val = Page_Validators[i];
      var ctrl = document.getElementById(val.controltovalidate);
      if (ctrl != null && ctrl.style != null)
      {
         if (!val.isvalid)
            ctrl.style.background = '#FFAAAA';
         else
            ctrl.style.backgroundColor = '';
      }
   }
}

The final step is to register the script with the OnSubmit event:

VB.NET:

Page.ClientScript.RegisterOnSubmitStatement(Me.GetType, "val", "fnOnUpdateValidators();")

C#:

Page.ClientScript.RegisterOnSubmitStatement(this.GetType(), "val", "fnOnUpdateValidators();");

You'll maintain the proper IsValid status in all of your code behind and it can work with all of your controls.

Note: I found this solution from the following blog. I just wanted to document it here in the event the source blog goes down.

月亮坠入山谷 2024-07-13 09:55:41

您可以非常轻松地重写 ASP.NET 的 javascript 函数来更新已验证字段的显示。 这是一个不错的选择,因为您可以保留现有的字段验证器,而不必编写任何自定义验证逻辑或寻找要验证的字段。 在下面的示例中,我从具有类“control-group”的父元素添加/删除“错误”类(因为我正在使用 twitter bootstrap css):

    /**
    * Re-assigns the ASP.NET validation JS function to
    * provide a more flexible approach
    */
    function UpgradeASPNETValidation() {
        if (typeof (Page_ClientValidate) != "undefined") {
            AspValidatorUpdateDisplay = ValidatorUpdateDisplay;
            ValidatorUpdateDisplay = NicerValidatorUpdateDisplay;
        }
    }

    /**
    * This function is called once for each Field Validator, passing in the 
    * Field Validator span, which has helpful properties 'isvalid' (bool) and
    * 'controltovalidate' (string = id of the input field to validate).
    */
    function NicerValidatorUpdateDisplay(val) {
        // Do the default asp.net display of validation errors (remove if you want)
        AspValidatorUpdateDisplay(val);

        // Add our custom display of validation errors
        if (val.isvalid) {
            // do whatever you want for invalid controls
            $('#' + val.controltovalidate).closest('.control-group').removeClass('error');
        } else {
            // reset invalid controls so they display as valid
            $('#' + val.controltovalidate).closest('.control-group').addClass('error');
        }
    }

    // Call UpgradeASPNETValidation after the page has loaded so that it 
    // runs after the standard ASP.NET scripts.
    $(document).ready(UpgradeASPNETValidation);

这是从 此处以及来自 这些文章

You can very easily override ASP.NET's javascript function that updates the display of validated fields. This is a nice option as you can keep your existing Field Validators, and don't have to write any custom validation logic or go looking for the fields to validate. In the example below I'm adding/removing an 'error' class from the parent element that has class 'control-group' (because I'm using twitter bootstrap css):

    /**
    * Re-assigns the ASP.NET validation JS function to
    * provide a more flexible approach
    */
    function UpgradeASPNETValidation() {
        if (typeof (Page_ClientValidate) != "undefined") {
            AspValidatorUpdateDisplay = ValidatorUpdateDisplay;
            ValidatorUpdateDisplay = NicerValidatorUpdateDisplay;
        }
    }

    /**
    * This function is called once for each Field Validator, passing in the 
    * Field Validator span, which has helpful properties 'isvalid' (bool) and
    * 'controltovalidate' (string = id of the input field to validate).
    */
    function NicerValidatorUpdateDisplay(val) {
        // Do the default asp.net display of validation errors (remove if you want)
        AspValidatorUpdateDisplay(val);

        // Add our custom display of validation errors
        if (val.isvalid) {
            // do whatever you want for invalid controls
            $('#' + val.controltovalidate).closest('.control-group').removeClass('error');
        } else {
            // reset invalid controls so they display as valid
            $('#' + val.controltovalidate).closest('.control-group').addClass('error');
        }
    }

    // Call UpgradeASPNETValidation after the page has loaded so that it 
    // runs after the standard ASP.NET scripts.
    $(document).ready(UpgradeASPNETValidation);

This is adapted ever-so-slightly from here and with helpful info from these articles.

情深已缘浅 2024-07-13 09:55:41

您可以使用 CustomValidator 代替RequiredFieldValidator:

.ASPX

<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage=""
    ControlToValidate="TextBox1" ClientValidationFunction="ValidateTextBox"
    OnServerValidate="CustomValidator1_ServerValidate"
    ValidateEmptyText="True"></asp:CustomValidator>

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

<script src="jquery-1.2.6.js" type="text/javascript"></script>
<script type="text/javascript">
    function ValidateTextBox(source, args)
    {
        var is_valid = $("#TextBox1").val() != "";
        $("#TextBox1").css("background-color", is_valid ? "white" : "red");
        args.IsValid = is_valid;
    }
</script>

.CS

protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
    bool is_valid = TextBox1.Text != "";
    TextBox1.BackColor = is_valid ? Color.White : Color.Red;
    args.IsValid = is_valid;
}

客户端和服务器验证函数中的逻辑是相同的,但客户端函数使用 jQuery 来访问文本框值并修改其值背景颜色。

You could use CustomValidator instead of RequiredFieldValidator:

.ASPX

<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage=""
    ControlToValidate="TextBox1" ClientValidationFunction="ValidateTextBox"
    OnServerValidate="CustomValidator1_ServerValidate"
    ValidateEmptyText="True"></asp:CustomValidator>

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

<script src="jquery-1.2.6.js" type="text/javascript"></script>
<script type="text/javascript">
    function ValidateTextBox(source, args)
    {
        var is_valid = $("#TextBox1").val() != "";
        $("#TextBox1").css("background-color", is_valid ? "white" : "red");
        args.IsValid = is_valid;
    }
</script>

.CS

protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
    bool is_valid = TextBox1.Text != "";
    TextBox1.BackColor = is_valid ? Color.White : Color.Red;
    args.IsValid = is_valid;
}

Logic in client and server validation functions is the same, but the client function uses jQuery to access textbox value and modify its background color.

梦幻之岛 2024-07-13 09:55:41

聚会已经很晚了,但为了防止其他人偶然发现这个问题并想要一个与 Bootstrap 一起使用的完整答案,我已经采用了上面的所有示例,并制作了一个可以与附加到单个控件的多个验证器一起使用的版本,并将与验证组一起工作:

<script>
    /**
    * Re-assigns the ASP.NET validation JS function to
    * provide a more flexible approach
    */
    function UpgradeASPNETValidation() {
        if (typeof (Page_ClientValidate) != "undefined") {
            AspValidatorUpdateDisplay = ValidatorUpdateDisplay;
            ValidatorUpdateDisplay = NicerValidatorUpdateDisplay;
            AspValidatorValidate = ValidatorValidate;
            ValidatorValidate = NicerValidatorValidate;

            // Remove the error class on each control group before validating
            // Store a reference to the ClientValidate function
            var origValidate = Page_ClientValidate;
            // Override with our custom version
            Page_ClientValidate = function (validationGroup) {
                // Clear all the validation classes for this validation group
                for (var i = 0; i < Page_Validators.length; i++) {
                    if ((typeof(Page_Validators[i].validationGroup) == 'undefined' && !validationGroup) ||
                        Page_Validators[i].validationGroup == validationGroup) {
                        $("#" + Page_Validators[i].controltovalidate).parents('.form-group').each(function () {
                            $(this).removeClass('has-error');
                        });
                    }
                }
                // Call the original function
                origValidate(validationGroup);
            };
        }
    }

    /**
    * This function is called once for each Field Validator, passing in the 
    * Field Validator span, which has helpful properties 'isvalid' (bool) and
    * 'controltovalidate' (string = id of the input field to validate).
    */
    function NicerValidatorUpdateDisplay(val) {
        // Do the default asp.net display of validation errors (remove if you want)
        AspValidatorUpdateDisplay(val);

        // Add our custom display of validation errors
        // IF we should be paying any attention to this validator at all
        if ((typeof (val.enabled) == "undefined" || val.enabled != false) && IsValidationGroupMatch(val, AspValidatorValidating)) {
            if (!val.isvalid) {
                // Set css class for invalid controls
                var t = $('#' + val.controltovalidate).parents('.form-group:first');
                t.addClass('has-error');
            }
        }
    }

    function NicerValidatorValidate(val, validationGroup, event) {
        AspValidatorValidating = validationGroup;
        AspValidatorValidate(val, validationGroup, event);
    }

    // Call UpgradeASPNETValidation after the page has loaded so that it 
    // runs after the standard ASP.NET scripts.
    $(function () {
        UpgradeASPNETValidation();
    });
</script>

Very late to the party, but just in case someone else stumbles across this and wants a complete answer which works with Bootstrap, I've taken all the examples above, and made a version which will work with multiple validators attached to a single control, and will work with validation groups:

<script>
    /**
    * Re-assigns the ASP.NET validation JS function to
    * provide a more flexible approach
    */
    function UpgradeASPNETValidation() {
        if (typeof (Page_ClientValidate) != "undefined") {
            AspValidatorUpdateDisplay = ValidatorUpdateDisplay;
            ValidatorUpdateDisplay = NicerValidatorUpdateDisplay;
            AspValidatorValidate = ValidatorValidate;
            ValidatorValidate = NicerValidatorValidate;

            // Remove the error class on each control group before validating
            // Store a reference to the ClientValidate function
            var origValidate = Page_ClientValidate;
            // Override with our custom version
            Page_ClientValidate = function (validationGroup) {
                // Clear all the validation classes for this validation group
                for (var i = 0; i < Page_Validators.length; i++) {
                    if ((typeof(Page_Validators[i].validationGroup) == 'undefined' && !validationGroup) ||
                        Page_Validators[i].validationGroup == validationGroup) {
                        $("#" + Page_Validators[i].controltovalidate).parents('.form-group').each(function () {
                            $(this).removeClass('has-error');
                        });
                    }
                }
                // Call the original function
                origValidate(validationGroup);
            };
        }
    }

    /**
    * This function is called once for each Field Validator, passing in the 
    * Field Validator span, which has helpful properties 'isvalid' (bool) and
    * 'controltovalidate' (string = id of the input field to validate).
    */
    function NicerValidatorUpdateDisplay(val) {
        // Do the default asp.net display of validation errors (remove if you want)
        AspValidatorUpdateDisplay(val);

        // Add our custom display of validation errors
        // IF we should be paying any attention to this validator at all
        if ((typeof (val.enabled) == "undefined" || val.enabled != false) && IsValidationGroupMatch(val, AspValidatorValidating)) {
            if (!val.isvalid) {
                // Set css class for invalid controls
                var t = $('#' + val.controltovalidate).parents('.form-group:first');
                t.addClass('has-error');
            }
        }
    }

    function NicerValidatorValidate(val, validationGroup, event) {
        AspValidatorValidating = validationGroup;
        AspValidatorValidate(val, validationGroup, event);
    }

    // Call UpgradeASPNETValidation after the page has loaded so that it 
    // runs after the standard ASP.NET scripts.
    $(function () {
        UpgradeASPNETValidation();
    });
</script>
扎心 2024-07-13 09:55:41

我喜欢 Rory 的答案,但它不适用于 ValidationGroups,尤其是在我的实例中,一个字段上有两个由两个不同按钮触发的验证器。

问题是,如果验证器不在当前的 ValidationGroup 中,ValidatorValidate 会将其标记为“isValid”,但我们的类更改代码没有任何关注。 这意味着显示不正确(当然IE9似乎不喜欢玩)。

所以为了解决这个问题,我做了以下更改:

    /**
    * Re-assigns the ASP.NET validation JS function to
    * provide a more flexible approach
    */
    function UpgradeASPNETValidation() {
        if (typeof (Page_ClientValidate) != "undefined") {
            AspValidatorUpdateDisplay = ValidatorUpdateDisplay;
            ValidatorUpdateDisplay = NicerValidatorUpdateDisplay;
            AspValidatorValidate = ValidatorValidate;
            ValidatorValidate = NicerValidatorValidate;
        }
    }

    /**
    * This function is called once for each Field Validator, passing in the 
    * Field Validator span, which has helpful properties 'isvalid' (bool) and
    * 'controltovalidate' (string = id of the input field to validate).
    */
    function NicerValidatorUpdateDisplay(val) {
        // Do the default asp.net display of validation errors (remove if you want)
        AspValidatorUpdateDisplay(val);

        // Add our custom display of validation errors
        // IF we should be paying any attention to this validator at all
        if ((typeof (val.enabled) == "undefined" || val.enabled != false) && IsValidationGroupMatch(val, AspValidatorValidating)) {
            if (val.isvalid) {
                // do whatever you want for invalid controls
                $('#' + val.controltovalidate).parents('.control-group:first').removeClass('error');
            } else {
                // reset invalid controls so they display as valid
                //$('#' + val.controltovalidate).parents('.control-group:first').addClass('error');
                var t = $('#' + val.controltovalidate).parents('.control-group:first');
                t.addClass('error');
            }
        }
    }

    function NicerValidatorValidate(val, validationGroup, event) {
        AspValidatorValidating = validationGroup;
        AspValidatorValidate(val, validationGroup, event);
    }

    // Call UpgradeASPNETValidation after the page has loaded so that it 
    // runs after the standard ASP.NET scripts.
    $(document).ready(UpgradeASPNETValidation);

I liked Rory's answer, but it doesn't work well with ValidationGroups, certainly in my instance where I have two validators on one field triggered by two different buttons.

The problem is that ValidatorValidate will mark the validator as 'isValid' if it is not in the current ValidationGroup, but our class-changing code does not pay any attention. This meant the the display was not correct (certainly IE9 seems to not like to play).

so to get around it I made the following changes:

    /**
    * Re-assigns the ASP.NET validation JS function to
    * provide a more flexible approach
    */
    function UpgradeASPNETValidation() {
        if (typeof (Page_ClientValidate) != "undefined") {
            AspValidatorUpdateDisplay = ValidatorUpdateDisplay;
            ValidatorUpdateDisplay = NicerValidatorUpdateDisplay;
            AspValidatorValidate = ValidatorValidate;
            ValidatorValidate = NicerValidatorValidate;
        }
    }

    /**
    * This function is called once for each Field Validator, passing in the 
    * Field Validator span, which has helpful properties 'isvalid' (bool) and
    * 'controltovalidate' (string = id of the input field to validate).
    */
    function NicerValidatorUpdateDisplay(val) {
        // Do the default asp.net display of validation errors (remove if you want)
        AspValidatorUpdateDisplay(val);

        // Add our custom display of validation errors
        // IF we should be paying any attention to this validator at all
        if ((typeof (val.enabled) == "undefined" || val.enabled != false) && IsValidationGroupMatch(val, AspValidatorValidating)) {
            if (val.isvalid) {
                // do whatever you want for invalid controls
                $('#' + val.controltovalidate).parents('.control-group:first').removeClass('error');
            } else {
                // reset invalid controls so they display as valid
                //$('#' + val.controltovalidate).parents('.control-group:first').addClass('error');
                var t = $('#' + val.controltovalidate).parents('.control-group:first');
                t.addClass('error');
            }
        }
    }

    function NicerValidatorValidate(val, validationGroup, event) {
        AspValidatorValidating = validationGroup;
        AspValidatorValidate(val, validationGroup, event);
    }

    // Call UpgradeASPNETValidation after the page has loaded so that it 
    // runs after the standard ASP.NET scripts.
    $(document).ready(UpgradeASPNETValidation);
離殇 2024-07-13 09:55:41

在 css 中:

       .form-control
        {
            width: 100px;
            height: 34px;
            padding: 6px 12px;
            font-size: 14px;
            color: black;
            background-color: white;
        }
        .form-control-Error
        {
            width: 100px;
            height: 34px;
            padding: 6px 12px;
            font-size: 14px;
            color: #EBB8C4;
            background-color: #F9F2F4
            border: 1px solid #DB7791;
            border-radius: 4px;
        }

在您的页面中:

<asp:TextBox ID="txtUserName" runat="server" CssClass="form-control"></asp:TextBox>
 <asp:RequiredFieldValidatorrunat="server"Display="Dynamic" ErrorMessage="PLease Enter UserName" ControlToValidate="txtUserName"></asp:RequiredFieldValidator>

在上面页面的末尾

<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 = "form-control-Error";
                    } else {
                        control.className = "form-control";
                    }
                } catch (e) { }
            }
            return false;
        }
        return true;
    }
</script>

in css:

       .form-control
        {
            width: 100px;
            height: 34px;
            padding: 6px 12px;
            font-size: 14px;
            color: black;
            background-color: white;
        }
        .form-control-Error
        {
            width: 100px;
            height: 34px;
            padding: 6px 12px;
            font-size: 14px;
            color: #EBB8C4;
            background-color: #F9F2F4
            border: 1px solid #DB7791;
            border-radius: 4px;
        }

in your page:

<asp:TextBox ID="txtUserName" runat="server" CssClass="form-control"></asp:TextBox>
 <asp:RequiredFieldValidatorrunat="server"Display="Dynamic" ErrorMessage="PLease Enter UserName" ControlToValidate="txtUserName"></asp:RequiredFieldValidator>

at the end of your page above of

<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 = "form-control-Error";
                    } else {
                        control.className = "form-control";
                    }
                } catch (e) { }
            }
            return false;
        }
        return true;
    }
</script>
浪漫之都 2024-07-13 09:55:41

我喜欢亚历山大的回答,但希望 JavaScript 更通用。 因此,这是一种消耗自定义验证器错误的通用方法。

    function ValidateTextBox(source, args) {
        var cntrl_id = $(source).attr("controltovalidate");
        var cntrl = $("#" + cntrl_id);
        var is_valid = $(cntrl).val() != "";
        is_valid ? $(cntrl).removeClass("error") : $(cntrl).addClass("error");

        args.IsValid = is_valid;
    }

I liked Alexander's answer, but wanted the javascript to be more generic. So, here is a generic way of consuming the errors from a custom validator.

    function ValidateTextBox(source, args) {
        var cntrl_id = $(source).attr("controltovalidate");
        var cntrl = $("#" + cntrl_id);
        var is_valid = $(cntrl).val() != "";
        is_valid ? $(cntrl).removeClass("error") : $(cntrl).addClass("error");

        args.IsValid = is_valid;
    }
纵性 2024-07-13 09:55:41

另一种可能性...这段代码为控件提供了一个红色边框(或者您在 CSS 类中放入的任何内容)以进行验证(适用于下拉列表和文本框,但可以扩展为按钮等...)

首先,我使用使用 CustomValidator 而不是RequiredFieldValidator,因为这样您就可以使用 CustomValidator 的 ClientValidationFunction 来更改要验证的控件的 CSS。

例如:当用户忘记填写文本框 MyTextBox 时,更改其边框。MyTextBox 控件的 CustomValidator 如下所示:

<asp:CustomValidator ID="CustomValidatorMyTextBox" runat="server" ErrorMessage=""
     Display="None" ClientValidationFunction="ValidateInput" 
     ControlToValidate="MyTextBox" ValidateEmptyText="true" 
     ValidationGroup="MyValidationGroup">
     </asp:CustomValidator>

或者它也适用于需要进行选择的下拉列表。 CustomValidator 看起来与上面相同,但 ControlToValidate 指向下拉列表。

对于客户端脚本,请使用 JQuery。 ValidateInput 方法如下所示:

    <script type="text/javascript">
    function ValidateInput(source, args)
    {
        var controlName = source.controltovalidate;
        var control = $('#' + controlName);
        if (control.is('input:text')) {
            if (control.val() == "") {
                control.addClass("validation");
                args.IsValid = false;
            }
            else {
                control.removeClass("validation");
                args.IsValid = true;
            }
        }
        else if (control.is('select')) {
            if (control.val() == "-1"[*] ) {
                control.addClass("validation");
                args.IsValid = false;
            }
            else {
                control.removeClass("validation");
                args.IsValid = true;
            }
        }
    }
    </script>

“validation”类是一个 CSS 类,其中包含触发验证器时的标记。 它可能看起来像这样:

.validation { border: solid 2px red; }

PS:为了使边框颜色适用于 IE 中的下拉列表,
将以下元标记添加到页面标题:

[*]这与RequiredFieldValidator的“InitialValue”相同。 这是当用户尚未选择任何内容时默认选择的项目。

Another possibility... this code gives a red border (or whatever you put inside the CSS class) to the control to validate (works for dropdownlists and textbox, but can be extended for buttons etc...)

First of, I make use of a CustomValidator instead of a RequiredFieldValidator, because then you can use the ClientValidationFunction of the CustomValidator to change the CSS of the control to validate.

For example: change the border of a textbox MyTextBox when a user forgot to fill it in. The CustomValidator for the MyTextBox control would look like this:

<asp:CustomValidator ID="CustomValidatorMyTextBox" runat="server" ErrorMessage=""
     Display="None" ClientValidationFunction="ValidateInput" 
     ControlToValidate="MyTextBox" ValidateEmptyText="true" 
     ValidationGroup="MyValidationGroup">
     </asp:CustomValidator>

Or it could also work for a dropdownlist in which a selection is required. The CustomValidator would look the same as above, but with the ControlToValidate pointing to the dropdownlist.

For the client-side script, make use of JQuery. The ValidateInput method would look like this:

    <script type="text/javascript">
    function ValidateInput(source, args)
    {
        var controlName = source.controltovalidate;
        var control = $('#' + controlName);
        if (control.is('input:text')) {
            if (control.val() == "") {
                control.addClass("validation");
                args.IsValid = false;
            }
            else {
                control.removeClass("validation");
                args.IsValid = true;
            }
        }
        else if (control.is('select')) {
            if (control.val() == "-1"[*] ) {
                control.addClass("validation");
                args.IsValid = false;
            }
            else {
                control.removeClass("validation");
                args.IsValid = true;
            }
        }
    }
    </script>

The “validation” class is a CSS class that contains the markup when the validator is fired. It could look like this:

.validation { border: solid 2px red; }

PS: to make the border color work for the dropdown list in IE,
add the following meta tag to the page's heading: <meta http-equiv="X-UA-Compatible" content="IE=edge" />.

[*]This is the same as the “InitialValue” of a RequiredFieldValidator. This is the item that is selected as default when the user hasn’t selected anything yet.​

海拔太高太耀眼 2024-07-13 09:55:41

我知道这已经很旧了,但我有另一个来自 Dillie-O 和 Alexander 的修改组合。 这使用 jQuery 和模糊事件来在验证成功时删除样式。

function validateFields() {
    try {
        var count = 0;
        var hasFocus = false;

        for (var i = 0; i < Page_Validators.length; i++) {
            var val = Page_Validators[i];
            var ctrl = document.getElementById(val.controltovalidate);

            validateField(ctrl, val);

            if (!val.isvalid) { count++; }
            if (!val.isvalid && hasFocus === false) {
                ctrl.focus(); hasFocus = true;
            }
        }

        if (count == 0) {
            hasFocus = false;
        }
    }
    catch (err) { }
}

function validateField(ctrl, val)
{
    $(ctrl).blur(function () { validateField(ctrl, val); });

    if (ctrl != null && $(ctrl).is(':disabled') == false) { // && ctrl.style != null
        val.isvalid ? $(ctrl).removeClass("error") : $(ctrl).addClass("error");
    }            

    if ($(ctrl).hasClass('rdfd_') == true) { //This is a RadNumericTextBox
        var rtxt = document.getElementById(val.controltovalidate + '_text');
        val.isvalid ? $(rtxt).removeClass("error") : $(rtxt).addClass("error");
    }
}

I know this is old, but I have another modified combination from Dillie-O and Alexander. This uses jQuery with the blur event to remove the style when validation succeeds.

function validateFields() {
    try {
        var count = 0;
        var hasFocus = false;

        for (var i = 0; i < Page_Validators.length; i++) {
            var val = Page_Validators[i];
            var ctrl = document.getElementById(val.controltovalidate);

            validateField(ctrl, val);

            if (!val.isvalid) { count++; }
            if (!val.isvalid && hasFocus === false) {
                ctrl.focus(); hasFocus = true;
            }
        }

        if (count == 0) {
            hasFocus = false;
        }
    }
    catch (err) { }
}

function validateField(ctrl, val)
{
    $(ctrl).blur(function () { validateField(ctrl, val); });

    if (ctrl != null && $(ctrl).is(':disabled') == false) { // && ctrl.style != null
        val.isvalid ? $(ctrl).removeClass("error") : $(ctrl).addClass("error");
    }            

    if ($(ctrl).hasClass('rdfd_') == true) { //This is a RadNumericTextBox
        var rtxt = document.getElementById(val.controltovalidate + '_text');
        val.isvalid ? $(rtxt).removeClass("error") : $(rtxt).addClass("error");
    }
}
一刻暧昧 2024-07-13 09:55:41

我也喜欢亚历山大和史蒂夫的回答,但我想要与代码隐藏相同的答案。 我认为这段代码可以做到这一点,但它会根据您的设置而有所不同。 我的控件位于内容占位符内。

protected void cvPhone_ServerValidate(object source, ServerValidateEventArgs args)
{
    bool is_valid = !string.IsNullOrEmpty(args.Value);
    string control = ((CustomValidator)source).ControlToValidate;
    ((TextBox)this.Master.FindControl("ContentBody").FindControl(control)).CssClass = is_valid ? string.Empty : "inputError";
    args.IsValid = is_valid;
}

I too liked Alexanders and Steves answer but I wanted the same as in codebehind. I think this code might do it but it differes depending on your setup. My controls are inside a contentplaceholder.

protected void cvPhone_ServerValidate(object source, ServerValidateEventArgs args)
{
    bool is_valid = !string.IsNullOrEmpty(args.Value);
    string control = ((CustomValidator)source).ControlToValidate;
    ((TextBox)this.Master.FindControl("ContentBody").FindControl(control)).CssClass = is_valid ? string.Empty : "inputError";
    args.IsValid = is_valid;
}
坏尐絯 2024-07-13 09:55:41

另一种方式,

$(document).ready(function() {
    HighlightControlToValidate();
    $('#<%=btnSave.ClientID %>').click(function() {
        if (typeof (Page_Validators) != "undefined") {
            for (var i = 0; i < Page_Validators.length; i++) {
                if (!Page_Validators[i].isvalid) {
                    $('#' + Page_Validators[i].controltovalidate).css("background", "#f3d74f");
                }
                else {
                    $('#' + Page_Validators[i].controltovalidate).css("background", "white");
                }
            }
        }
    });
});

参考:
http://www.codedigest.com/Articles/ASPNET/414_Highlight_Input_Controls_when_Validation_fails_in_AspNet_Validator_controls.aspx

Another way,

$(document).ready(function() {
    HighlightControlToValidate();
    $('#<%=btnSave.ClientID %>').click(function() {
        if (typeof (Page_Validators) != "undefined") {
            for (var i = 0; i < Page_Validators.length; i++) {
                if (!Page_Validators[i].isvalid) {
                    $('#' + Page_Validators[i].controltovalidate).css("background", "#f3d74f");
                }
                else {
                    $('#' + Page_Validators[i].controltovalidate).css("background", "white");
                }
            }
        }
    });
});

Reference:
http://www.codedigest.com/Articles/ASPNET/414_Highlight_Input_Controls_when_Validation_fails_in_AspNet_Validator_controls.aspx

动次打次papapa 2024-07-13 09:55:41

我为常规 asp.net 制作了一个有效的寻呼机示例,没有 .control-group

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html>
<!-- http://stackoverflow.com/questions/196859/change-text-box-color-using-required-field-validator-no-extender-controls-pleas -->
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
    <script>
        /**
  * Re-assigns the ASP.NET validation JS function to
  * provide a more flexible approach
  */
        function UpgradeASPNETValidation() {
            if (typeof (Page_ClientValidate) != "undefined") {
                AspValidatorUpdateDisplay = ValidatorUpdateDisplay;
                ValidatorUpdateDisplay = NicerValidatorUpdateDisplay;
                AspValidatorValidate = ValidatorValidate;
                ValidatorValidate = NicerValidatorValidate;
            }
        }

        /**
        * This function is called once for each Field Validator, passing in the 
        * Field Validator span, which has helpful properties 'isvalid' (bool) and
        * 'controltovalidate' (string = id of the input field to validate).
        */
        function NicerValidatorUpdateDisplay(val) {
            // Do the default asp.net display of validation errors (remove if you want)
            AspValidatorUpdateDisplay(val);

            // Add our custom display of validation errors
            // IF we should be paying any attention to this validator at all
            if ((typeof (val.enabled) == "undefined" || val.enabled != false) && IsValidationGroupMatch(val, AspValidatorValidating)) {
                if (val.isvalid) {
                    // do whatever you want for invalid controls
                    $('#' + val.controltovalidate).removeClass('error');
                } else {
                    // reset invalid controls so they display as valid
                    //$('#' + val.controltovalidate).parents('.control-group:first').addClass('error');
                    var t = $('#' + val.controltovalidate);
                    t.addClass('error');
                }
            }
        }

        function NicerValidatorValidate(val, validationGroup, event) {
            AspValidatorValidating = validationGroup;
            AspValidatorValidate(val, validationGroup, event);
        }

        // Call UpgradeASPNETValidation after the page has loaded so that it 
        // runs after the standard ASP.NET scripts.
        $(document).ready(UpgradeASPNETValidation);
    </script>
    <style>
        .error {
            border: 1px solid red;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>

        <asp:TextBox ID="TextBox1" runat="server" ></asp:TextBox>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1" ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator>
        <asp:Button ID="Button1" runat="server" Text="Button" />

        <br />
        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
        <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="TextBox2" ErrorMessage="RegularExpressionValidator" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>
        <br />
        <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
        <asp:RangeValidator ID="RangeValidator1" runat="server" ControlToValidate="TextBox3" ErrorMessage="RangeValidator" MaximumValue="100" MinimumValue="0"></asp:RangeValidator>

    </div>
    </form>
</body>
</html>

I made a working one pager example of this for regular asp.net, no .control-group

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html>
<!-- http://stackoverflow.com/questions/196859/change-text-box-color-using-required-field-validator-no-extender-controls-pleas -->
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
    <script>
        /**
  * Re-assigns the ASP.NET validation JS function to
  * provide a more flexible approach
  */
        function UpgradeASPNETValidation() {
            if (typeof (Page_ClientValidate) != "undefined") {
                AspValidatorUpdateDisplay = ValidatorUpdateDisplay;
                ValidatorUpdateDisplay = NicerValidatorUpdateDisplay;
                AspValidatorValidate = ValidatorValidate;
                ValidatorValidate = NicerValidatorValidate;
            }
        }

        /**
        * This function is called once for each Field Validator, passing in the 
        * Field Validator span, which has helpful properties 'isvalid' (bool) and
        * 'controltovalidate' (string = id of the input field to validate).
        */
        function NicerValidatorUpdateDisplay(val) {
            // Do the default asp.net display of validation errors (remove if you want)
            AspValidatorUpdateDisplay(val);

            // Add our custom display of validation errors
            // IF we should be paying any attention to this validator at all
            if ((typeof (val.enabled) == "undefined" || val.enabled != false) && IsValidationGroupMatch(val, AspValidatorValidating)) {
                if (val.isvalid) {
                    // do whatever you want for invalid controls
                    $('#' + val.controltovalidate).removeClass('error');
                } else {
                    // reset invalid controls so they display as valid
                    //$('#' + val.controltovalidate).parents('.control-group:first').addClass('error');
                    var t = $('#' + val.controltovalidate);
                    t.addClass('error');
                }
            }
        }

        function NicerValidatorValidate(val, validationGroup, event) {
            AspValidatorValidating = validationGroup;
            AspValidatorValidate(val, validationGroup, event);
        }

        // Call UpgradeASPNETValidation after the page has loaded so that it 
        // runs after the standard ASP.NET scripts.
        $(document).ready(UpgradeASPNETValidation);
    </script>
    <style>
        .error {
            border: 1px solid red;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>

        <asp:TextBox ID="TextBox1" runat="server" ></asp:TextBox>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1" ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator>
        <asp:Button ID="Button1" runat="server" Text="Button" />

        <br />
        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
        <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="TextBox2" ErrorMessage="RegularExpressionValidator" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>
        <br />
        <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
        <asp:RangeValidator ID="RangeValidator1" runat="server" ControlToValidate="TextBox3" ErrorMessage="RangeValidator" MaximumValue="100" MinimumValue="0"></asp:RangeValidator>

    </div>
    </form>
</body>
</html>
水中月 2024-07-13 09:55:41

这里有一些独立的 HTML/JS 可以实现这个目的:

<html>
  <head>
    <script type="text/javascript">
      function mkclr(cntl,clr) {
        document.getElementById(cntl).style.backgroundColor = clr;
      };
    </script>
  </head>
  <body>
    <form>
      <input type="textbox" id="tb1"></input>
      <input type="submit" value="Go"
        onClick="javascript:mkclr('tb1','red');">
      </input>
    </form>
  </body>
</html>

Here's some self-contained HTML/JS that does the trick:

<html>
  <head>
    <script type="text/javascript">
      function mkclr(cntl,clr) {
        document.getElementById(cntl).style.backgroundColor = clr;
      };
    </script>
  </head>
  <body>
    <form>
      <input type="textbox" id="tb1"></input>
      <input type="submit" value="Go"
        onClick="javascript:mkclr('tb1','red');">
      </input>
    </form>
  </body>
</html>
£噩梦荏苒 2024-07-13 09:55:41

我必须对史蒂夫的建议进行一些更改才能让我的建议正常工作,

 function ValidateTextBox(source, args) {
    var controlId = document.getElementById(source.controltovalidate).id;
    var control = $("#" + controlId);
    var value = control.val();
    var is_valid = value != "";
    is_valid ? control.removeClass("error") : control.addClass("error");
    args.IsValid = is_valid;
  }

尽管这是一个很好的例子,但正是我所需要的。

I had to make a few changes to Steve's suggestion to get mine working,

 function ValidateTextBox(source, args) {
    var controlId = document.getElementById(source.controltovalidate).id;
    var control = $("#" + controlId);
    var value = control.val();
    var is_valid = value != "";
    is_valid ? control.removeClass("error") : control.addClass("error");
    args.IsValid = is_valid;
  }

great example though, exactly what I needed.

浅浅淡淡 2024-07-13 09:55:41
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Custemvalidatin.aspx.cs" Inherits="AspDotNetPractice.Custemvalidatin" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
        function vali(source, args) {
            if (document.getElementById(source.controltovalidate).value.length > 0) {
                args.IsValid = true;
                document.getElementById(source.controltovalidate).style.borderColor = 'green';
            }
            else {
                args.IsValid = false;
                document.getElementById(source.controltovalidate).style.borderColor = 'red';
            }

        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:TextBox ID="TextBox1" Style="border:1px solid gray; width:270px; height:24px ; border-radius:6px;"   runat="server"></asp:TextBox>

            <asp:CustomValidator ID="CustomValidator1" runat="server" ControlToValidate="TextBox1"
                ErrorMessage="Enter First Name" SetFocusOnError="True" Display="Dynamic" ClientValidationFunction="vali" 
                ValidateEmptyText="True" Font-Size="Small" ForeColor="Red">Enter First Name</asp:CustomValidator><br /><br /><br />

            <asp:TextBox ID="TextBox2" Style="border:1px solid gray; width:270px; height:24px ; border-radius:6px;"  runat="server"></asp:TextBox>

            <asp:CustomValidator ID="CustomValidator2" runat="server" ClientValidationFunction="vali"
                ControlToValidate="TextBox2" Display="Dynamic" ErrorMessage="Enter Second Name"
                SetFocusOnError="True" ValidateEmptyText="True" Font-Size="Small" ForeColor="Red">Enter Second Name</asp:CustomValidator><br />
            <br />
            <br />

            <asp:Button ID="Button1" runat="server" Text="Button" />
        </div>
    </form>
</body>
</html>
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Custemvalidatin.aspx.cs" Inherits="AspDotNetPractice.Custemvalidatin" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
        function vali(source, args) {
            if (document.getElementById(source.controltovalidate).value.length > 0) {
                args.IsValid = true;
                document.getElementById(source.controltovalidate).style.borderColor = 'green';
            }
            else {
                args.IsValid = false;
                document.getElementById(source.controltovalidate).style.borderColor = 'red';
            }

        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:TextBox ID="TextBox1" Style="border:1px solid gray; width:270px; height:24px ; border-radius:6px;"   runat="server"></asp:TextBox>

            <asp:CustomValidator ID="CustomValidator1" runat="server" ControlToValidate="TextBox1"
                ErrorMessage="Enter First Name" SetFocusOnError="True" Display="Dynamic" ClientValidationFunction="vali" 
                ValidateEmptyText="True" Font-Size="Small" ForeColor="Red">Enter First Name</asp:CustomValidator><br /><br /><br />

            <asp:TextBox ID="TextBox2" Style="border:1px solid gray; width:270px; height:24px ; border-radius:6px;"  runat="server"></asp:TextBox>

            <asp:CustomValidator ID="CustomValidator2" runat="server" ClientValidationFunction="vali"
                ControlToValidate="TextBox2" Display="Dynamic" ErrorMessage="Enter Second Name"
                SetFocusOnError="True" ValidateEmptyText="True" Font-Size="Small" ForeColor="Red">Enter Second Name</asp:CustomValidator><br />
            <br />
            <br />

            <asp:Button ID="Button1" runat="server" Text="Button" />
        </div>
    </form>
</body>
</html>
深爱成瘾 2024-07-13 09:55:41

这并不完全不需要改变用户习惯的控件,但我认为这种方式更容易(不写完整的示例,我认为没有必要):

ASP.NET:

    <asp:TextBox ID="TextBox1" runat="server" ></asp:TextBox>
    <asp:CustomValidator runat="server" ControlToValidate="TextBox1" Display="Dynamic" Text="TextBox1 Not Set" ValidateEmptyText="true" OnServerValidate="ServerValidate" />
    <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Execute" />

代码:

protected void Execute(object sender, EventArgs e)
{
   Page.Validate();
   if (Page.IsValid)
   {
       *some code*
   }
}

protected void ServerValidate(object source, ServerValidateEventArgs args)
{
    CustomValidator cval = source as CustomValidator;
    if (cval == null)
    {
        args.IsValid = false;
        return;
    }

    if (string.IsNullOrEmpty(args.Value))
    {
        args.IsValid = false;
        string _target = cval.ControlToValidate;
        TextBox tb = cval.Parent.FindControl(_target) as TextBox;
        tb.BorderColor = System.Drawing.Color.Red;
    }
    else
    {
        args.IsValid = true;
    }
}

It is not exactly without changing controls user used to, but I think this way is easier (not writing the full example, I think it is not necessary):

ASP.NET:

    <asp:TextBox ID="TextBox1" runat="server" ></asp:TextBox>
    <asp:CustomValidator runat="server" ControlToValidate="TextBox1" Display="Dynamic" Text="TextBox1 Not Set" ValidateEmptyText="true" OnServerValidate="ServerValidate" />
    <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Execute" />

Code:

protected void Execute(object sender, EventArgs e)
{
   Page.Validate();
   if (Page.IsValid)
   {
       *some code*
   }
}

protected void ServerValidate(object source, ServerValidateEventArgs args)
{
    CustomValidator cval = source as CustomValidator;
    if (cval == null)
    {
        args.IsValid = false;
        return;
    }

    if (string.IsNullOrEmpty(args.Value))
    {
        args.IsValid = false;
        string _target = cval.ControlToValidate;
        TextBox tb = cval.Parent.FindControl(_target) as TextBox;
        tb.BorderColor = System.Drawing.Color.Red;
    }
    else
    {
        args.IsValid = true;
    }
}
神爱温柔 2024-07-13 09:55:41

我结合了很多答案,现在我有了一些非常适合我的东西:

Css:

input[type=text] {
    border: 1px solid #ccc;
}

.ErrorControl {
    background-color: #FBE3E4;
    border-color: Red !important;
}

ASPX输入文本+验证:

 <label>First name</label>
 <asp:TextBox ID="tbFirstName" runat="server" CssClass="form-control text-box" onchange="javascript:text_changed(this);"></asp:TextBox>
 <div class="error-message-validators">
     <asp:RequiredFieldValidator ID="rfvName" runat="server" ValidationGroup="AccountDetails" ControlToValidate="tbFirstName" Display="Dynamic" ClientValidationFunction="highlightInvalidTextbox" ErrorMessage="Please enter your name"  />
     <asp:RegularExpressionValidator ID="revNameFormat" runat="server" ValidationGroup="AccountDetails" ControlToValidate="tbFirstName" Display="Dynamic" ValidationExpression="^[^\\<>`"*%:?]*$" ErrorMessage="You cannot use \ < > ` " * % : ?  in your name." />
 </div>

然后您需要在关闭正文标记之前直接在页面末尾添加此脚本:

<script type="text/javascript">
    function IsFieldValid(fieldId) {
        var validators = Page_Validators.filter(x => x.controltovalidate == fieldId);

        if (validators != undefined) {
            for (var i in validators) {
                if (!validators[i].isvalid)
                    return false;
            }

            return true;
        }
    }
    function text_changed(textObj) {
        var includesErrorControlClass = textObj.className != null  && textObj.className.includes("ErrorControl");
        if (IsFieldValid(textObj.id) && includesErrorControlClass) {
            textObj.className = textObj.className.replace("ErrorControl", "");
        }
        else if (!IsFieldValid(textObj.id) && !includesErrorControlClass) {
            textObj.className = "form-control text-box ErrorControl";
        }
    }
    function WebForm_OnSubmit() {
        if (typeof (ValidatorOnSubmit) == "function" && ValidatorOnSubmit() == false) {
            var previousValidation = false;
            var previousControlId = "";
            for (var i in Page_Validators) {
                try {
                    var control = document.getElementById(Page_Validators[i].controltovalidate);

                    if (previousControlId == Page_Validators[i].controltovalidate && previousValidation == false) {
                        continue;
                    }

                    if (!Page_Validators[i].isvalid) {
                        control.className = "form-control text-box ErrorControl";
                    } else {
                        control.className = "form-control";
                    }

                    previousControlId = Page_Validators[i].controltovalidate;
                    previousValidation = Page_Validators[i].isvalid;
                } catch (e) { }
            }
            return false;
        }
        return true;
    }
</script>

I combined a lot of answers and now I have something that works perfectly for me:

Css:

input[type=text] {
    border: 1px solid #ccc;
}

.ErrorControl {
    background-color: #FBE3E4;
    border-color: Red !important;
}

ASPX input text + validations:

 <label>First name</label>
 <asp:TextBox ID="tbFirstName" runat="server" CssClass="form-control text-box" onchange="javascript:text_changed(this);"></asp:TextBox>
 <div class="error-message-validators">
     <asp:RequiredFieldValidator ID="rfvName" runat="server" ValidationGroup="AccountDetails" ControlToValidate="tbFirstName" Display="Dynamic" ClientValidationFunction="highlightInvalidTextbox" ErrorMessage="Please enter your name"  />
     <asp:RegularExpressionValidator ID="revNameFormat" runat="server" ValidationGroup="AccountDetails" ControlToValidate="tbFirstName" Display="Dynamic" ValidationExpression="^[^\\<>`"*%:?]*
quot; ErrorMessage="You cannot use \ < > ` " * % : ?  in your name." />
 </div>

Then you need to add this script straight at the end of the page just before you close the body tag:

<script type="text/javascript">
    function IsFieldValid(fieldId) {
        var validators = Page_Validators.filter(x => x.controltovalidate == fieldId);

        if (validators != undefined) {
            for (var i in validators) {
                if (!validators[i].isvalid)
                    return false;
            }

            return true;
        }
    }
    function text_changed(textObj) {
        var includesErrorControlClass = textObj.className != null  && textObj.className.includes("ErrorControl");
        if (IsFieldValid(textObj.id) && includesErrorControlClass) {
            textObj.className = textObj.className.replace("ErrorControl", "");
        }
        else if (!IsFieldValid(textObj.id) && !includesErrorControlClass) {
            textObj.className = "form-control text-box ErrorControl";
        }
    }
    function WebForm_OnSubmit() {
        if (typeof (ValidatorOnSubmit) == "function" && ValidatorOnSubmit() == false) {
            var previousValidation = false;
            var previousControlId = "";
            for (var i in Page_Validators) {
                try {
                    var control = document.getElementById(Page_Validators[i].controltovalidate);

                    if (previousControlId == Page_Validators[i].controltovalidate && previousValidation == false) {
                        continue;
                    }

                    if (!Page_Validators[i].isvalid) {
                        control.className = "form-control text-box ErrorControl";
                    } else {
                        control.className = "form-control";
                    }

                    previousControlId = Page_Validators[i].controltovalidate;
                    previousValidation = Page_Validators[i].isvalid;
                } catch (e) { }
            }
            return false;
        }
        return true;
    }
</script>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文