Reset an asp.net validation control via javascript? - asp.net

How do I reset an asp.net validation control via JavaScript? The current code sample clears the error message text but does not reset the validation control for the next form submission.
var cv= document.getElementById("<%= MyValidationContorl.ClientID %>");
cv.innerHTML = '';
Update:
Here is the full code sample of the form. I can not seem to get the validation controls fire off on another form submission:
function ClearData() {
var cv = document.getElementById("<%= MyValidationContorl.ClientID %>");
cv.innerHTML = '';
}
<html>
<form>
<asp:TextBox id="MyTextControl" runat="server" />
<asp:CustomValidator ID="MyValidationContorl" runat="server" />
<input type="button" onclick="javascript:ClearCCData(); return false;" runat="server" />
</form>
</html>

Page validation is fired every time you do a post, what appears to be the problem is that you are clearing the validator content cv.innerHTML = '';, this way your validator message is lost forever and you'll think validation is not firing again.
and for #Glennular answer, the code does not handle the validator Display property, if its set to Dynamic the validator will be toggled using validator.style.display, but if its set to None or Inline then validator.style.visibility property will be used instead.
Its better to use asp.net ValidatorUpdateDisplay instead,
<script type="text/javascript">
function Page_ClientValidateReset() {
if (typeof (Page_Validators) != "undefined") {
for (var i = 0; i < Page_Validators.length; i++) {
var validator = Page_Validators[i];
validator.isvalid = true;
ValidatorUpdateDisplay(validator);
}
}
}
</script>
Update : Reset Validation Summaries
<script type="text/javascript">
function Page_ValidationSummariesReset(){
if (typeof(Page_ValidationSummaries) == "undefined")
return;
for (var i = 0; i < Page_ValidationSummaries.length; i++)
Page_ValidationSummaries[i].style.display = "none";
}
</script>

This one resets all validators in all validation groups.
<script type="text/javascript">
Page_ClientValidate('');
</script>

Try the following chunk of code :
$("#<%= txtUserSettingsEmailRequiredValidator.ClientID %>").css("display", "none");
I hope this will work as it worked for me. :)

Here's code to reset all validators
function CleanForm() {
document.forms[0].reset();
for (i = 0; i < Page_Validators.length; i++) {
Page_Validators[i].style.visibility = 'hidden';
}
return false;
}
or a single one:
document.getElementById("<%= MyValidationContorl.ClientID %>").style.visibility
= 'hidden';

Using the Page_Validators[i].style.visibility = 'hidden';
Don't work for me so I use this line of code instead: Page_Validators[i].enabled = false;
if (sFirstName == "" && sLastName == "")
{
alert('Reminder: Please first enter student ID to search for the student information before filling out the rest of the form field values');
//Disable all require field validation coontrol on the form so the user could continue to use the Lookup student function.
document.forms[0].reset();
for (i = 0; i < Page_Validators.length; i++) {
//Page_Validators[i].style.visibility = 'hidden';
Page_Validators[i].enabled = false;
}
return false;
}
else
{
alert('Student Name = ' + sFirstName + ' ' + sLastName);
document.forms[0].reset();
for (i = 0; i < Page_Validators.length; i++) {
//Page_Validators[i].style.visibility = 'hidden';
Page_Validators[i].enabled = true;
}
return true;
}

Related

Iterate through the model object in javascript (foreach and <text>)

As going through the site i got how to access the model in javascript and how to loop it in javascript.
i am using text tag to access the item in a model. when i use i am not able to add break.
#foreach (var item in Model.ArrayDetails)
{
var checklower = false;
var checkUpper = false;
var loopentered = false;
<text>
if(#item.Id ==1)
{
if(#item.LowerBound <= obj.value)
{
loopentered=true;
checklower=true;
}
if(loopentered)
{
alert(#item.UpperBound <= obj.value);
if(#item.UpperBound <= obj.value)
{
checkUpper = true;
}
}
if(checkUpper && checklower)
{
***// here i want to add break statement(if i add javascript wont work)***
}
}
</text>
}
Can some one suggest me how can solve this.
Don't write this soup. JSON serialize your model into a javascript variable and use this javascript variable to write your javascript code. Right now you have a terrible mixture of server side and client side code.
Here's what I mean in practice:
<script type="text/javascript">
// Here we serialize the Model.ArrayDetails into a javascript array
var items = #Html.Raw(Json.Encode(Model.ArrayDetails));
// This here is PURE javascript, it could (AND IT SHOULD) go into
// a separate javascript file containing this logic to which you could
// simply pass the items variable
for (var i = 0; i < items.length; i++) {
var item = items[i];
var checklower = false;
var checkUpper = false;
var loopentered = false;
if (item.Id == 1) {
if (item.LowerBound <= obj.value) {
loopentered = true;
checklower = true;
}
if (loopentered) {
alert(item.UpperBound <= obj.value);
if(item.UpperBound <= obj.value) {
checkUpper = true;
}
}
if (checkUpper && checklower) {
break;
}
}
}
</script>
and after moving the javascript into a separate file your view will simply become:
<script type="text/javascript">
// Here we serialize the Model.ArrayDetails into a javascript array
var items = #Html.Raw(Json.Encode(Model.ArrayDetails));
myFunctionDefinedIntoASeparateJavaScriptFile(items);
</script>

Page Got Postback in OnClientClick Return False

I am working in C#.Net. i am having an asp button..
<asp:Button ID="btnSubmitData" ToolTip="Show" runat="server" Text="SHOW" CausesValidation="false"
OnClientClick="return FindSelectedItems();" OnClick="btnShow_Click" />
The function called in OnClientClick is,
function FindSelectedItems() {
var sender = document.getElementById('lstMultipleValues');
var cblstTable = document.getElementById(sender.id);
var checkBoxPrefix = sender.id + "_";
var noOfOptions = cblstTable.rows.length;
var selectedText = "";
var total = 0;
for (i = 0; i < noOfOptions; ++i) {
if (document.getElementById(checkBoxPrefix + i).checked) {
total += 1;
if (selectedText == "")
selectedText = document.getElementById
(checkBoxPrefix + i).parentNode.innerText;
else
selectedText = selectedText + "," +
document.getElementById(checkBoxPrefix + i).parentNode.innerText;
}
}
var hifMet1 = document.getElementById('<%=hifMet1.ClientID%>');
hifMet1.value = selectedText;
if (total == 0) {
var panel = document.getElementById('<%=pnlOk.ClientID%>');
document.getElementById('<%=pnlOk.ClientID%>').style.display = 'block';
var Label1 = document.getElementById('<%=Label3.ClientID%>');
Label1.innerHTML = "Atleast one metric should be selected.";
var btnLoc = document.getElementById('<%=btnLoc.ClientID%>');
btnLoc.disabled = true;
var btnProd = document.getElementById('<%=btnProd.ClientID%>');
btnProd.disabled = true;
var btnLastYear = document.getElementById('<%=btnLastYear.ClientID%>');
btnLastYear.disabled = true;
return false;
}
else if (total > 2) {
var panel = document.getElementById('<%=pnlOk.ClientID%>');
document.getElementById('<%=pnlOk.ClientID%>').style.display = 'block';
var Label1 = document.getElementById('<%=Label3.ClientID%>');
Label1.innerHTML = "Only two metrics can be compared.";
var btnLoc = document.getElementById('<%=btnLoc.ClientID%>');
btnLoc.disabled = true;
var btnProd = document.getElementById('<%=btnProd.ClientID%>');
btnProd.disabled = true;
var btnLastYear = document.getElementById('<%=btnLastYear.ClientID%>');
btnLastYear.disabled = true;
return false;
}
else {
return true;
}
}
Once i click the SHOW Button, i need to do a validation to check at least one checkbox should get checked in checkbox list. That alert message i am getting (i.e) "Atleast one metric should be selected". But after this part, the page gets reloaded.
I want to avoid the page refresh at this point. What should i do here.?
One way is to hook your validation function into the proper ASP .Net validation lifecycle by using a CustomValidator control and a client validation function.
With a few minor changes you can turn your JavaScript code into a client validation function.
Full example here.
Relevant Snippets
<script language="javascript">
function ClientValidate(source, arguments)
{
// Your code would go here, and set the IsValid property of arguments instead
// of returning true/false
if (arguments.Value % 2 == 0 ){
arguments.IsValid = true;
} else {
arguments.IsValid = false;
}
}
</script>
<asp:CustomValidator id="CustomValidator1"
ControlToValidate="Text1"
ClientValidationFunction="ClientValidate"
OnServerValidate="ServerValidation"
Display="Static"
ErrorMessage="Not an even number!"
ForeColor="green"
Font-Name="verdana"
Font-Size="10pt"
runat="server"/>
<asp:Button id="Button1"
Text="Validate"
OnClick="ValidateBtn_OnClick"
runat="server"/>
Client validation should always be double-checked with server validation; using a CustomValidator with both client/server validation functions is a good way to accomplish this.
Remove script
else {
return true;
}
part from script and call function like this
OnClientClick="javascript:return FindSelectedItems();"
This work for me.

Problem with a button's OnClientClick event inside an UpdatePanel

im using javascript like
var TargetBaseControl = null;
window.onload = function()
{
try
{
//get target base control.
TargetBaseControl =
document.getElementById('<%= this.GridView1.ClientID %>');
}
catch(err)
{
TargetBaseControl = null;
}
}
function TestCheckBox()
{
if(TargetBaseControl == null) return false;
//get target child control.
var TargetChildControl = "chkSelect";
//get all the control of the type INPUT in the base control.
var Inputs = TargetBaseControl.getElementsByTagName("input");
for(var n = 0; n < Inputs.length; ++n)
if(Inputs[n].type == 'checkbox' &&
Inputs[n].id.indexOf(TargetChildControl,0) >= 0 &&
Inputs[n].checked)
return true;
alert('Select at least one checkbox!');
return false;
}
and inside the update panel i have code like
<asp:Button ID="ButtonSave" runat="server" OnClick="ButtonSave_Click"
OnClientClick="javascript:return TestCheckBox();" Text="Save" />
when i run the page and click the button then no more further processing just button has been click nothing happan......
Try this:
function TestCheckBox()
{
var TargetBaseControl = null;
if(TargetBaseControl = document.getElementById('<%= this.GridView1.ClientID %>')){
//get target child control.
var TargetChildControl = "chkSelect";
//get all the control of the type INPUT in the base control.
var Inputs = TargetBaseControl.getElementsByTagName("input");
for(var n = 0; n < Inputs.length; ++n)
if(Inputs[n].type == 'checkbox' &&
Inputs[n].id.indexOf(TargetChildControl,0) >= 0 &&
Inputs[n].checked)
return true;
}
alert('Select at least one checkbox!');
return false;
}
look at the source of your page once it is in a browser.
see what happens with the OnClientClick assignment.
does it get rewritten/re-routed ?
it should be pretty clear at that point.
you can also step through with tools such as Firebug in firefox, IE8 developer tools, chrome developer tools, or visual studio

Change textbox's css class when ASP.NET Validation fails

How can I execute some javascript when a Required Field Validator attached to a textbox fails client-side validation? What I am trying to do is change the css class of the textbox, to make the textbox's border show red.
I am using webforms and I do have the jquery library available to me.
Here is quick and dirty thing (but it works!)
<form id="form1" runat="server">
<asp:TextBox ID="txtOne" runat="server" />
<asp:RequiredFieldValidator ID="rfv" runat="server"
ControlToValidate="txtOne" Text="SomeText 1" />
<asp:TextBox ID="txtTwo" runat="server" />
<asp:RequiredFieldValidator ID="rfv2" runat="server"
ControlToValidate="txtTwo" Text="SomeText 2" />
<asp:Button ID="btnOne" runat="server" OnClientClick="return BtnClick();"
Text="Click" CausesValidation="true" />
</form>
<script type="text/javascript">
function BtnClick() {
//var v1 = "#<%= rfv.ClientID %>";
//var v2 = "#<%= rfv2.ClientID %>";
var val = Page_ClientValidate();
if (!val) {
var i = 0;
for (; i < Page_Validators.length; i++) {
if (!Page_Validators[i].isvalid) {
$("#" + Page_Validators[i].controltovalidate)
.css("background-color", "red");
}
}
}
return val;
}
</script>
You could use the following script:
<script>
$(function(){
if (typeof ValidatorUpdateDisplay != 'undefined') {
var originalValidatorUpdateDisplay = ValidatorUpdateDisplay;
ValidatorUpdateDisplay = function (val) {
if (!val.isvalid) {
$("#" + val.controltovalidate).css("border", "2px solid red");
}
originalValidatorUpdateDisplay(val);
}
}
});
</script>
This code decorates the original ValidatorUpdateDisplay function responsible for updating the display of your validators, updating the controltovalidate as necessary.
Hope this helps,
I think you would want to use a Custom Validator and then use the ClientValidationFunction... Unless it helpfully adds a css class upon fail.
Some time ago I spend a few hours on it and since then I have been using some custom js magic to accomplish this.
In fact is quite simple and in the way that ASP.NET validation works. The basic idea is add a css class to attach a javascript event on each control you want quick visual feedback.
<script type="text/javascript" language="javascript">
/* Color ASP NET validation */
function validateColor(obj) {
var valid = obj.Validators;
var isValid = true;
for (i in valid)
if (!valid[i].isvalid)
isValid = false;
if (!isValid)
$(obj).addClass('novalid', 1000);
else
$(obj).removeClass('novalid', 1000);
}
$(document).ready(function() {
$(".validateColor").change(function() {validateColor(this);});
});
</script>
For instance, that will be the code to add on an ASP.Net textbox control. Yes, you can put as many as you want and it will only imply add a CssClass value.
<asp:TextBox ID="txtBxEmail" runat="server" CssClass="validateColor" />
What it does is trigger ASP.Net client side validation when there is a change on working control and apply a css class if it's not valid. So to customize visualization you can rely on css.
.novalid {
border: 2px solid #D00000;
}
It's not perfect but almost :) and at least your code won't suffer from extra stuff. And
the best, works with all kind of Asp.Net validators, event custom ones.
I haven't seen something like this googling so I wan't to share my trick with you. Hope it helps.
extra stuff on server side:
After some time using this I also add this ".novalid" css class from code behind when need some particular validation on things that perhaps could be only checked on server side this way:
Page.Validate();
if (!requiredFecha.IsValid || !CustomValidateFecha.IsValid)
txtFecha.CssClass = "validateColor novalid";
else
txtFecha.CssClass = "validateColor";
Here is my solution.
Advantages over other solutions:
Integrates seamlessly with ASP.NET - NO changes required to code. Just call the method on page load in a master page.
Automatically changes the CSS class when the text box or control changes
Disadvantages:
Uses some internal features of ASP.NET JavaScript code
Tested only on ASP.NET 4.0
HOW TO USE:
Requires JQuery
Call the "Validation_Load" function when the page loads
Declare a "control_validation_error" CSS class
function Validation_Load() {
if (typeof (Page_Validators) != "object") {
return;
}
for (var i = 0; i < Page_Validators.length; i++) {
var val = Page_Validators[i];
var control = $("#" + val.controltovalidate);
if (control.length > 0) {
var tagName = control[0].tagName;
if (tagName != "INPUT" && tagName != "TEXTAREA" && tagName != "SELECT") {
// Validate sub controls
}
else {
// Validate the control
control.change(function () {
var validators = this.Validators;
if (typeof (validators) == "object") {
var isvalid = true;
for (var k = 0; k < validators.length; k++) {
var val = validators[k];
if (val.isvalid != true) {
isvalid = false;
break;
}
}
if (isvalid == true) {
// Clear the error
$(this).removeClass("control_validation_error");
}
else {
// Show the error
$(this).addClass("control_validation_error");
}
}
});
}
}
}
}
Alternatively, just iterate through the page controls as follows: (needs a using System.Collections.Generic reference)
const string CSSCLASS = " error";
protected static Control FindControlIterative(Control root, string id)
{
Control ctl = root;
LinkedList<Control> ctls = new LinkedList<Control>();
while ( ctl != null )
{
if ( ctl.ID == id ) return ctl;
foreach ( Control child in ctl.Controls )
{
if ( child.ID == id ) return child;
if ( child.HasControls() ) ctls.AddLast(child);
}
ctl = ctls.First.Value;
ctls.Remove(ctl);
}
return null;
}
protected void Page_PreRender(object sender, EventArgs e)
{
//Add css classes to invalid items
if ( Page.IsPostBack && !Page.IsValid )
{
foreach ( BaseValidator item in Page.Validators )
{
var ctrltoVal = (WebControl)FindControlIterative(Page.Form, item.ControlToValidate);
if ( !item.IsValid ) ctrltoVal.CssClass += " N";
else ctrltoVal.CssClass.Replace(" N", "");
}
}
}
Should work for most cases, and means you dont have to update it when you add validators. Ive added this code into a cstom Pageclass so it runs site wide on any page I have added validators to.

Change Text Box Color using Required Field Validator. No Extender Controls Please

I need to change color of TextBox whenever its required field validator is fired on Clicking the Submit button
What you can do is register a Javascript function that will iterate through the global Page_Validators array after submission and you can set the background appropriately. The nice thing about this is that you can use it on all of your controls on the page. The function looks like this:
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 = '';
}
}
}
The final step is to register the script with the OnSubmit event:
VB.NET:
Page.ClientScript.RegisterOnSubmitStatement(Me.GetType, "val", "fnOnUpdateValidators();")
C#:
Page.ClientScript.RegisterOnSubmitStatement(this.GetType(), "val", "fnOnUpdateValidators();");
You'll maintain the proper IsValid status in all of your code behind and it can work with all of your controls.
Note: I found this solution from the following blog. I just wanted to document it here in the event the source blog goes down.
You can very easily override ASP.NET's javascript function that updates the display of validated fields. This is a nice option as you can keep your existing Field Validators, and don't have to write any custom validation logic or go looking for the fields to validate. In the example below I'm adding/removing an 'error' class from the parent element that has class 'control-group' (because I'm using 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);
This is adapted ever-so-slightly from here and with helpful info from these articles.
You could use CustomValidator instead of 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;
}
Logic in client and server validation functions is the same, but the client function uses jQuery to access textbox value and modify its background color.
Very late to the party, but just in case someone else stumbles across this and wants a complete answer which works with Bootstrap, I've taken all the examples above, and made a version which will work with multiple validators attached to a single control, and will work with validation groups:
<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>
I liked Rory's answer, but it doesn't work well with ValidationGroups, certainly in my instance where I have two validators on one field triggered by two different buttons.
The problem is that ValidatorValidate will mark the validator as 'isValid' if it is not in the current ValidationGroup, but our class-changing code does not pay any attention. This meant the the display was not correct (certainly IE9 seems to not like to play).
so to get around it I made the following changes:
/**
* 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);
in 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;
}
in your page:
<asp:TextBox ID="txtUserName" runat="server" CssClass="form-control"></asp:TextBox>
<asp:RequiredFieldValidatorrunat="server"Display="Dynamic" ErrorMessage="PLease Enter UserName" ControlToValidate="txtUserName"></asp:RequiredFieldValidator>
at the end of your page above of
<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>
I liked Alexander's answer, but wanted the javascript to be more generic. So, here is a generic way of consuming the errors from a custom validator.
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;
}
Another possibility... this code gives a red border (or whatever you put inside the CSS class) to the control to validate (works for dropdownlists and textbox, but can be extended for buttons etc...)
First of, I make use of a CustomValidator instead of a RequiredFieldValidator, because then you can use the ClientValidationFunction of the CustomValidator to change the CSS of the control to validate.
For example: change the border of a textbox MyTextBox when a user forgot to fill it in. The CustomValidator for the MyTextBox control would look like this:
<asp:CustomValidator ID="CustomValidatorMyTextBox" runat="server" ErrorMessage=""
Display="None" ClientValidationFunction="ValidateInput"
ControlToValidate="MyTextBox" ValidateEmptyText="true"
ValidationGroup="MyValidationGroup">
</asp:CustomValidator>
Or it could also work for a dropdownlist in which a selection is required. The CustomValidator would look the same as above, but with the ControlToValidate pointing to the dropdownlist.
For the client-side script, make use of JQuery. The ValidateInput method would look like this:
<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>
The “validation” class is a CSS class that contains the markup when the validator is fired. It could look like this:
.validation { border: solid 2px red; }
PS: to make the border color work for the dropdown list in IE,
add the following meta tag to the page's heading: <meta http-equiv="X-UA-Compatible" content="IE=edge" />.
[*]This is the same as the “InitialValue” of a RequiredFieldValidator. This is the item that is selected as default when the user hasn’t selected anything yet.​
I know this is old, but I have another modified combination from Dillie-O and Alexander. This uses jQuery with the blur event to remove the style when validation succeeds.
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");
}
}
I too liked Alexanders and Steves answer but I wanted the same as in codebehind. I think this code might do it but it differes depending on your setup. My controls are inside a 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;
}
Another way,
$(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");
}
}
}
});
});
Reference:
http://www.codedigest.com/Articles/ASPNET/414_Highlight_Input_Controls_when_Validation_fails_in_AspNet_Validator_controls.aspx
I made a working one pager example of this for regular asp.net, no .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>
Here's some self-contained HTML/JS that does the trick:
<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>
I had to make a few changes to Steve's suggestion to get mine working,
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;
}
great example though, exactly what I needed.
<%# 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>
It is not exactly without changing controls user used to, but I think this way is easier (not writing the full example, I think it is not necessary):
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" />
Code:
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;
}
}

Resources