如何在需要时突出显示文本框边框红色?

时间:2014-01-20 15:31:32

标签: asp.net webforms

如果存在验证错误,我在必需的字段验证程序控件上使用什么属性来使文本框变为红色?

这是我的代码:

<asp:Label ID="lblFirstName" runat="server" AssociatedControlID="txtFirstName" Text="First Name:" CssClass="reg-labels" />
<br />
<asp:TextBox ID="txtFirstName" runat="server" CausesValidation="true" MaxLength="60" CssClass="standard_width"/>
<asp:RequiredFieldValidator ControlToValidate="txtFirstName" runat="server" ID="valFirstName" ValidationGroup="grpRegistration" ErrorMessage="First Name is required." Text="*" />

5 个答案:

答案 0 :(得分:16)

ASP.Net网络表单在内部使用位于aspnet_client\{0}\{1}文件夹的Javascript框架来处理验证等。它们基本上是从属性ClientScriptsLocation确定的

尝试覆盖默认框架功能,方法是将其保留在页面中,其他行包含设置control_to_validate颜色

document.getElmentById(val.controltovalidate).style.border='1px solid red';

<asp:TextBox ID="txtFirstName" runat="server" CausesValidation="true" MaxLength="60"
    CssClass="standard_width" />
<asp:RequiredFieldValidator ControlToValidate="txtFirstName" runat="server" ID="valFirstName" ValidationGroup="grpRegistration" ErrorMessage="First Name is required." Text="*" />
<asp:Button Text="Super" ID="btnSubmit" CausesValidation="true" runat="server" />

JS

<script type="text/javascript">
    function ValidatorUpdateDisplay(val) {
        if (typeof (val.display) == "string") {
            if (val.display == "None") {
                return;
            }
            if (val.display == "Dynamic") {
                val.style.display = val.isvalid ? "none" : "inline";
                return;
            }

        }
        val.style.visibility = val.isvalid ? "hidden" : "visible";
        if (val.isvalid) {
            document.getElementById(val.controltovalidate).style.border = '1px solid #333';
        }
        else {
            document.getElementById(val.controltovalidate).style.border = '1px solid red';
        }          
    }
</script>

答案 1 :(得分:10)

如果不重载任何内容,请为<asp:*Validator代码添加CssClass="garbage"属性。

在样式表中,创建

.garbage {
    display: none;
}
.garbage[style*=visible] + input,
.garbage[style*=visible] + select,
.garbage[style*=visible] + textarea {
    background-color: #ffcccc;
    border: 1px solid #ff0000;
}

,任何紧接在验证器之前的表单控件都将在无效数据上突出显示。

编辑:

我见过一些在Chrome中强制重绘的方法,包括纯css解决方案:transform: translateZ(0);

答案 2 :(得分:2)

Murali的答案很有效,但如果有兴趣的话,我会为自己推出一个jQuery版本。

根据官方文档(https://msdn.microsoft.com/en-us/library/yb52a4x0.aspx),我能够获取每个验证器并检查它是否isvalid,如果没有,请使用errormessage属性填充我的自己的通知系统(setStatusMessage()是我写的一个函数,随时可以使用任何其他类型的状态消息提示,如alert()或自己动手)。

/*
*   Validation Catcher - Sean D Kendle - 9/24/2015
*   Catch validation events and add to status messages system
*/
$(document).on("submit", function () {
    $.each(Page_Validators, function (i, v) {
        var strControlToValidateID = v.controltovalidate;
        var $controlToValidate = $("#" + strControlToValidateID);

        var arrInvalidControls = new Array(); //collection of all invalid field ids for later

        if (!v.isvalid) {
            $controlToValidate.addClass("error"); //custom error class, optional
            $controlToValidate.css("border-color", "#D00"); //manually set border-color per OP's question

            $(".error").eq(0).focus(); /*set focus to top-most invalid field on error, or you can use the v.focusOnError property to check if validator has this set (string "t" if true), but I don't want to have to set this every time*/

            arrInvalidControls.push(strControlToValidateID);  //collect all invalid field ids for later

            $(v).addClass("redtext"); //custom class - allows me to make all errors red without having to add a ForeColor property to every validator

            setStatusMessage(v.errormessage, "red", -1); // setStatusMessage is a function I wrote, replace with another alert system if desired, or delete this line
        } else {
            /*the following prevents control being seen as valid if there are two or more validators for the control - example:  required field validator, then custom or regex validator (first would be invalid, second would be valid for empty field)*/
            if (!$.inArray(strControlToValidateID, arrInvalidControls)) {
                $controlToValidate.removeClass("error");
                $controlToValidate.css("border-color", "");
            } else {
                //console.log(strControlToValidateID + " is already invalid.");
            }
        }
    });
});

我希望这有助于某人!

答案 3 :(得分:1)

嗯,令你失望的是没有直接的方式(cf https://stackoverflow.com/a/5249021/145682

但是,您可以使用CustomValidator。以下是定义它的一种方法:

<asp:TextBox ID="txtbx" runat="server"></asp:TextBox>
<asp:CustomValidator ID="customValidator" 
    runat="server" ValidationGroup="submit" ControlToValidate="txtbx" 
    ClientValidationFunction="foo" ErrorMessage="*"></asp:CustomValidator>

记下ClientValidationFunction。它必须写成如下:

    function foo(sender, e) {
        var value = e.Value;
        console.log('Value: ', e.Value);
        var ctrlid = sender.controltovalidate;
        var targetControl = document.getElementById(ctrlid);
        if (vowels.indexOf(value[0].toLowerCase()) == -1) {
            console.log('true-executed');
            e.isValid = false;
            targetControl.style.borderColor = 'red';
        }
        else {
            console.log('else-executed');
            e.isValid = true;
            targetControl.style.borderColor = '';
        }
    }

controltovalidate的{​​{1}}属性会为您提供您正在寻找的控件的ID;换句话说,就是你的sender。并且,ControlToValidate的{​​{1}}属性应该为您提供目标控件的值。

另一个选择是,您可以编写自己的服务器控件来完成工作:http://msdn.microsoft.com/en-us/library/aa719624(v=vs.71).aspx

答案 4 :(得分:1)

Murali的回答对我来说在数据更改时起作用,但在回发时所有呈现的字段都没有验证错误。我发现ASP.NET延迟加载ValidatorUpdateDisplay,因此客户端覆盖直到它已经通过其onload验证后才会生效。我猜这里有一个版本或一个实现差异阻止了我,但是其他解决方案(包括一些CSS)也无法正常工作。

最终,我找到了一个解决方案,将Murali的答案与Dillie-O的解决方案结合起来:Change Text Box Color using Required Field Validator. No Extender Controls Please

b--

这个解决方案的优点在于它可以让您通过向验证器添加<div class="pad-left"> <asp:CompareValidator ID="comvIncTaxable" runat="server" ControlToValidate="tbIncTaxable" Display="Dynamic" Operator="DataTypeCheck" Type="Currency" CssClass="red-border" ErrorMessage="Please enter a currency value."> <span></span> </asp:CompareValidator> <asp:TextBox runat="server" ID="tbIncTaxable"></asp:TextBox> </div> <script type="text/javascript"> $(function () { setValidatedBordersOnLoad(); }); function ValidatorUpdateDisplay(val) { if (typeof (val.display) == "string") { if (val.display == "None") { return; } if (val.display == "Dynamic") { val.style.display = val.isvalid ? "none" : "inline"; if (val.className == 'red-border' && val.controltovalidate) { if (val.isvalid) { document.getElementById(val.controltovalidate).style.border = '1px solid #ccc'; } else { document.getElementById(val.controltovalidate).style.border = '1px solid red'; } } return; } } val.style.visibility = val.isvalid ? "hidden" : "visible"; } function setValidatedBordersOnLoad() { for (var i = 0; i < Page_Validators.length; i++) { var val = Page_Validators[i]; if (val.className == 'red-border' && val.controltovalidate) { var ctrl = document.getElementById(val.controltovalidate); if (ctrl != null && ctrl.style != null) { if (!val.isvalid) ctrl.style.border = '1px solid red'; else ctrl.style.border = '1px solid #ccc'; } } } } </script> 来挑选哪些验证器获得此特殊处理。就我而言,我只想在特定网格中的字段上进行此行为,其中单元格定位不应更改,但仍希望在表单的其他位置使用现成功能。