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

时间:2008-10-13 06:35:19

标签: asp.net servercontrols requiredfieldvalidator

我需要在单击“提交”按钮

时触发所需的字段验证器时更改TextBox的颜色

16 个答案:

答案 0 :(得分: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 = '';
      }
   }
}

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

VB.NET:

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

C#:

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

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

注意:我从following blog找到了这个解决方案。我只想在源博客发布的情况下将其记录在案。

答案 1 :(得分:18)

您可以非常轻松地覆盖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);

此问题从here开始略微调整,并且来自these articles的有用信息。

答案 2 :(得分: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>

<强> .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访问文本框值并修改其背景颜色。

答案 3 :(得分: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>

答案 4 :(得分:4)

我喜欢Rory的答案,但它与ValidationGroups不兼容,当然在我的实例中,我在两个不同按钮触发的一个字段上有两个验证器。

问题是ValidatorValidate会将验证器标记为'isValid',如果它不在当前的ValidationGroup中,但是我们的类更改代码没有引起任何注意。这意味着显示不正确(当然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);

答案 5 :(得分:4)

在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>

答案 6 :(得分:3)

我喜欢Alexander的答案,但希望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;
    }

答案 7 :(得分:2)

我知道这是旧的,但我有另一个来自Dillie-O和Alexander的改良组合。这使用带有blur事件的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");
    }
}

答案 8 :(得分:2)

另一种可能性......这段代码给控件提供了一个红色边框(或者你放在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中的下拉列表, 将以下元标记添加到页面的标题:<meta http-equiv="X-UA-Compatible" content="IE=edge" />

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

答案 9 :(得分:1)

我也很喜欢Alexanders和Steves的回答,但我想要与代码隐藏相同。我认为这段代码可能会这样做,但它根据您的设置而有所不同。我的控件位于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;
}

答案 10 :(得分:1)

另一种方式,

$(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

答案 11 :(得分:1)

我为常规的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>

答案 12 :(得分: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>

答案 13 :(得分:0)

我不得不对史蒂夫的建议进行一些修改,让我的工作,

 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;
  }

很好的例子,正是我需要的。

答案 14 :(得分:0)

<%@ 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>

答案 15 :(得分:0)

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

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;
    }
}