使用必填字段validation程序更改文本框颜色。 没有扩展控制请

每当需要的字段validation器被触发时,我需要改变TextBox的颜色点击Submitbutton

你可以做的是注册一个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状态,并且可以使用所有的控件。

注意:我从以下博客find了这个解决scheme。 我只是想在这里logging源博客的故事。

你可以很容易地重写ASP.NET的javascript函数来更新validation字段的显示。 这是一个不错的select,因为您可以保留现有的字段validation器,而不必编写任何自定义validation逻辑或查找字段进行validation。 在下面的例子中,我添加/删除类“控制组”的父元素(因为我使用twitter引导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); 

这是从这里稍微适应,并从这些 文章的有用信息。

您可以使用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; } 

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

这个派对很晚,但为了防止其他人在这个问题上磕磕绊绊,想要一个可以与Bootstrap结合的完整答案,我已经把上面的所有例子都做了,并且制作了一个可以和多个validation器一起工作的版本,并将与validation组一起工作:

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

我喜欢Rory的答案,但它不适用于ValidationGroups,当然在我的实例中,有两个validation器在一个字段上由两个不同的button触发。

问题是ValidatorValidate将validation器标记为“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); 

我喜欢亚历山大的答案,但希望JavaScript是更通用的。 所以,这里是一个消费自定义validation器错误的通用方式。

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

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

另一种可能性…这个代码给了控件validation的红色边框(或者你放在CSS类中的任何东西)(适用于下拉列表和文本框,但是可以扩展为button等)

首先,我使用一个CustomValidator而不是一个RequiredFieldValidator,因为那么你可以使用CustomValidator的ClientValidationFunction来改变控件的CSS来validation。

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

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

或者它也可以用于需要select的下拉列表。 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器被激发时的标记。 它可能是这样的:

 .validation { border: solid 2px red; } 

PS:为IE中的下拉列表设置边框颜色,将下面的元标记添加到页面标题中: <meta http-equiv="X-UA-Compatible" content="IE=edge" />

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

我知道这已经很老了,但我还有另外一个来自Dillie-O和Alexander的组合。 这使用jQuery与blur事件来validation成功时删除样式。

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

我也喜欢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; } 

其他方式,

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

我做了一个正常的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> 

这里有一些独立的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> 

我不得不对史蒂夫的build议做一些改变,让我的工作,

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

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

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

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

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