使用必填字段验证器更改文本框颜色.没有扩展器控制请

24 asp.net servercontrols requiredfieldvalidator

我需要在单击"提交"按钮时触发所需的字段验证器时更改TextBox的颜色

Dil*_*e-O 26

你可以做的是注册一个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 = '';
      }
   }
}
Run Code Online (Sandbox Code Playgroud)

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

VB.NET:

Page.ClientScript.RegisterOnSubmitStatement(Me.GetType, "val", "fnOnUpdateValidators();")
Run Code Online (Sandbox Code Playgroud)

C#:

Page.ClientScript.RegisterOnSubmitStatement(this.GetType(), "val", "fnOnUpdateValidators();");
Run Code Online (Sandbox Code Playgroud)

您将在所有代码中保持正确的IsValid状态,并且它可以与您的所有控件一起使用.

注意:我从以下博客中找到了此解决方案.我只想在源博客发布的情况下将其记录在案.


Ror*_*ory 18

您可以非常轻松地覆盖ASP.NET的javascript函数,该函数更新已验证字段的显示.这是一个不错的选项,因为您可以保留现有的字段验证器,而不必编写任何自定义验证逻辑或查找要验证的字段.在下面的例子中,我在具有类'control-group'的父元素中添加/删除'error'类(因为我使用的是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);
Run Code Online (Sandbox Code Playgroud)

这是从这里稍微适应的,并从这些 文章中获得有用的信息.

  • 这对我需要的东西很有用.谢谢. (2认同)

Ale*_*yev 13

您可以使用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>
Run Code Online (Sandbox Code Playgroud)

.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;
}
Run Code Online (Sandbox Code Playgroud)

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

  • 如果jquery不存在,可以使用`function ValidateTextBox(source,args){var target = document.getElementById("TextBox1"); var is_valid = target.value!=""; if(is_valid){target.style.backgroundColor ="White"; } else {target.style.backgroundColor ="Red"; } args.IsValid = is_valid; }` (2认同)

use*_*644 5

派对很晚,但是为了防止其他人偶然发现并想要一个与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>
Run Code Online (Sandbox Code Playgroud)


pax*_*blo 0

这里有一些独立的 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>
Run Code Online (Sandbox Code Playgroud)