使用必填字段验证器更改文本框颜色。请不要扩展器控制
Posted
技术标签:
【中文标题】使用必填字段验证器更改文本框颜色。请不要扩展器控制【英文标题】:Change Text Box Color using Required Field Validator. No Extender Controls Please 【发布时间】:2010-09-16 20:19:49 【问题描述】:每当单击提交按钮时触发其必填字段验证器时,我都需要更改 TextBox 的颜色
【问题讨论】:
我用过这个:gist.github.com/meziantou/1755cd2d21c8a1d1d148 【参考方案1】:您可以做的是注册一个 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 找到了这个解决方案。我只是想在源博客出现故障时将其记录在这里。
【讨论】:
我喜欢这个解决方案——我自己做的一个改变是允许一个控件有多个验证器。无法编辑帖子,所以不知道如何分享它。 WebForm_OnSubmit 在哪里?我已经搜索了我的整个项目,但找不到对它的引用 @sQuijeW 您是否使用了上面的“最后一步”代码?这会将操作注册到适当的事件。 @Dillie-O 我需要在代码中编写最后一条语句(page.clien.....)(是否在文件后面的代码中)请您帮忙... @pratapk 您需要将该 Page.ClientScript 代码放在代码隐藏文件中的 Page_Load 方法中,以便它始终在回发后注册脚本。【参考方案2】:您可以非常轻松地覆盖 ASP.NET 的 javascript 函数,该函数会更新已验证字段的显示。这是一个不错的选择,因为您可以保留现有的字段验证器,而不必编写任何自定义验证逻辑或去寻找要验证的字段。在下面的示例中,我正在从具有类“控制组”的父元素中添加/删除一个“错误”类(因为我使用的是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 的有用信息。
【讨论】:
当控件有多个验证器时工作方式错误。 这是个好主意。我试图找到一种方法来劫持现有的验证内容,这是完美的。只要这些函数名称不变。谢谢!不过,我认为您的 cmets 倒退了有效/无效。【参考方案3】:您可以使用 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来访问文本框的值并修改它的背景颜色。
【讨论】:
如果 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;
如果无效,这会阻止回发吗?【参考方案4】:
晚会很晚,但以防万一其他人偶然发现这一点并想要一个与 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>
【讨论】:
【参考方案5】:我喜欢 Rory 的回答,但它不适用于 ValidationGroups,当然在我的例子中,我在一个字段上有两个验证器,由两个不同的按钮触发。
问题是ValidatorValidate如果不在当前的ValidationGroup中,就会将validator标记为'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);
【讨论】:
非常好!但是,如果我有多个与控件关联的验证器,这对我来说确实会中断。只有最后一个验证器有任何影响,因为它会覆盖之前的任何验证器(即,如果 css 类有效,它将删除它,即使前面的验证器之一失败)。【参考方案6】:在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>
【讨论】:
【参考方案7】:我喜欢 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;
【讨论】:
【参考方案8】:另一种可能性...此代码为控件提供了一个红色边框(或您在 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>
“验证”类是一个 CSS 类,其中包含验证器被触发时的标记。它可能看起来像这样:
.validation border: solid 2px red;
PS:让边框颜色适用于 IE 中的下拉列表,
将以下元标记添加到页面标题:<meta http-equiv="X-UA-Compatible" content="IE=edge" />
。
[*]这与RequiredFieldValidator 的“InitialValue”相同。这是用户尚未选择任何内容时默认选择的项目。
【讨论】:
【参考方案9】:我知道这是旧的,但我有另一个来自 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");
【讨论】:
【参考方案10】:我也很喜欢 Alexanders 和 Steves 的回答,但我想要和代码隐藏中的一样。我认为这段代码可能会这样做,但它会根据您的设置而有所不同。我的控件位于内容占位符内。
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;
【讨论】:
【参考方案11】:另一种方式,
$(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
【讨论】:
欢迎来到 Stack Overflow!虽然这在理论上可以回答这个问题,但我们希望您在回答中包含链接文章的基本部分,并提供link for reference。不这样做会使答案面临链接失效的风险。【参考方案12】:我为常规的 asp.net 制作了一个有效的单页机示例,没有 .control-group
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<!-- http://***.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>
【讨论】:
【参考方案13】:这里有一些独立的 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>
【讨论】:
【参考方案14】:我必须对史蒂夫的建议进行一些更改才能让我的工作正常,
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;
很好的例子,正是我需要的。
【讨论】:
【参考方案15】:<%@ 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>
【讨论】:
【参考方案16】:这并不是完全不改变用户习惯的控件,但我认为这种方式更容易(不写完整的例子,我认为没有必要):
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;
【讨论】:
以上是关于使用必填字段验证器更改文本框颜色。请不要扩展器控制的主要内容,如果未能解决你的问题,请参考以下文章
如何在 WooCommerce 中更改必填字段星号颜色 [关闭]