I have a gridview that contains one to many rows (like most do) - each with an input textbox. Each row has a requiredfieldvalidator against that textbox. When the form is submitted the gridview is validated it is entirely possible that more than one row has an empty textbox. This results in repeating validation messages e.g.
Please provide text for 'Name' field
Please provide text for 'Name' field
Please provide text for 'Name' field
Is it possible to consolidate these messages into one message?
I know it possible to create a validator by setting up a validator class and inheriting from BaseValidator class which can be used to validate the gridview as a whole. But I put an image against each row when it is invalid so I should imagine I require separate validators on each row.
This is a solution that uses a CustomValidator and requires a few organizational changes. This requires a postback since CustomValidator validation is performed on the server-side.
Here's the setup:
For each of your existing RequiredFieldValidators that display the "Please provide text for 'Name' field" message you will need to set:
EnableClientScript="false"
ValidationGroup="vgTxtName" (provide your own name)
ErrorMessage="" (or remove it altogether; the CustomValidator will now be responsible for this)
You have the option of displaying nothing at all (less clear to the user) or displaying an asterisk to indicate which validator is invalid.
Option 1:
Display="None"
Option 2 (preferred):
Display="Dynamic"
Set the text in between the validator tags to: *
No changes needed for your ValidationSummary control (it should be neutral and not have a ValidationGroup attribute set, which is the default)
Add a CustomValidator (see code below)
Add an eventhandler for the CustomValidator's ServerValidate event (you can just double click it from the designer to have it generated)
Implement the eventhandler logic (see code below)
The idea is not to directly allow the page to handle those RequiredFieldValidators anymore and instead we'll let the CustomValidator do it.
TextBox RequiredFieldValidator example (you should have something that looks like this with relevant ID names which corresponds to step 1 above):
Option 1:
<asp:RequiredFieldValidator ControlToValidate="txt1" ID="rfv1" runat="server"
EnableClientScript="false" Display="None" ValidationGroup="vgTxtName" />
Option 2:
<asp:RequiredFieldValidator ControlToValidate="txt1" ID="rfv1" runat="server"
EnableClientScript="false" Display="Dynamic" ValidationGroup="vgTxtName">*
</asp:RequiredFieldValidator>
CustomValidator Markup (you can place this anywhere sensible, such as next to the ValidationSummary control):
<asp:CustomValidator ID="cvName" runat="server" Display="None"
ErrorMessage="Please provide text for 'Name' field"
OnServerValidate="cvName_ServerValidate" />
The error message here replaces the ones from the individual validators. Also notice there's no ControlToValidate set, which is valid for this type of validator and is useful for applying validation covering multiple controls.
CustomValidator EventHandler (cvName_ServerValidate):
protected void cvName_ServerValidate(object source, ServerValidateEventArgs args)
{
// Validate vgTxtName group
Page.Validate("vgTxtName");
// .NET 3.5 - add using System.Linq;
args.IsValid = Page.GetValidators("vgTxtName")
.OfType<RequiredFieldValidator>()
.All(v => v.IsValid);
// .NET 2.0 (use either this or the above, not both)
bool isValid = true;
foreach (RequiredFieldValidator validator in Page.GetValidators("vgTxtName"))
{
isValid &= validator.IsValid;
}
args.IsValid = isValid;
}
That's it! Just bear in mind that this is strictly for RequiredFieldValidators. You shouldn't place different types of validators in the "vgTxtName" group since the cvName logic deals strictly with the RequiredFieldValidator type. You'll need to setup different groupings or tweak the code if you intend to use other validator types.
I would suggest not using a Validator Summary.
Change the Text property or inner content of the validators to something more appropriate for your application.
For example...
<asp:Validator ID="X" ... runAt="server" Text="*" />
or
<asp:Validator ID="X" ... runAt="server">*</asp:Validator>
or to display an image...
<asp:Validator ID="X" ... runAt="server"><img src="../path.png" alt="Invalid" /></asp:Validator>
I also style the validator to change to pointer to the help cursor and add a ToolTip property to show the same Error Message.
Related
Is there a way to validate asp.net text box for input using built-in validators for two distinct conditions? The text box is used in conjunction with a date picker and presently I have RegularExpressionValidator like this to validate:
<asp:TextBox ID="tbStartDate" runat="server" Width="100" CssClass="TextCompact">yyyy</asp:TextBox>
<asp:HyperLink ID="hlStartDate" runat="server" ImageUrl="~/Images/iconCalendar.gif"></asp:HyperLink><br />
<asp:RegularExpressionValidator ID="revStartDate" ControlToValidate="tbStartDate"
CssClass="TextCompact" runat="server" ErrorMessage="* Invalid Date" ValidationExpression="^(\d{4})$" />
which fires everytime an invalid date is entered - you can use the date picker or you can type in a date string.
So the issue is that I only want to validate if there is data in the text box. If the text box is empty I want it to pass through without validation.
Is this possible or would a custom client side validation be required?
Thanks,
Risho.
Update:
I've decided to write my own validator class derived from the BaseValidator class and wired it up but I get a compiler error.
namespace Abcdefg1234
{
public class Custom_Validator : BaseValidator
{
public Custom_Validator()
{
}
protected override bool EvaluateIsValid()
{
String value = this.GetControlValidationValue(this.ControlToValidate);
return ValidateControls(value.Trim());
}
public static bool ValidateControls(string value)
{
if(Regex.IsMatch(value, #"^(\d{4})$") == true)
return true;
else if(value == "")
return true;
else
return false;
}
}
}
Then I included the page directive tag:
<%# Register TagPrefix="Cv" Namespace="Abcdefg1234" TagName="CustomValidaitonX" %>
and the actual tag:
Cv:Custom_Validator ID="cvtbStartDate" ControlToValidate="tbStartDate" runat="server" ErrorMessage="* Invalid Date" />
I get a unknown server tag. Any ideas? Thanks.
The only built-in validator that fires on an empty text box would be the RequiredFieldValidator. If a textbox is empty, the other validators associated with it won't fire on form submission.
In other words, you should be fine just as you are, with the RegularExpressionValidator not firing if you submit with the textbox still empty. Are you experiencing different behavior?
ETA: You need to specify the Assembly name in your Register page directive for the Custom_Validator to be recognized. I don't believe the tag name is required for a custom control.
I have a text box control in asp with 3 different validators. Each validator is getting its error message from the server, and each one validates different things.
My problem is that for some values, two or more validators are firing and I'm getting more then one error message.
I would like to make some kind of priority functionality, meaning that if the first validator is firing the other two will not. Is there any way to make the validator behave like that?
I've added some code sample:
<asp:RequiredFieldValidator ID="cvRequired" runat="server" Display="Dynamic"
ControlToValidate="txtBox" />
<asp:RegularExpressionValidator ID="cvFormat" runat="server" Display="Dynamic"
ControlToValidate="txtBox" ValidationExpression="^([A-Za-z])+$" />
<asp:CustomValidator ID="cvCustom" runat="server" Display="Dynamic"
ControlToValidate="txtBox" ClientValidationFunction="validateFunction" />
I want that the format validator and the custom validator will not fire if the required validator is invalid (actually, I just want them to not showing their error message).
As I said, the error messages are from the server, so I can't really join them to one custom validator. Also, the "validateFunction" is in another js file (for re-use).
Few logic options you got to think about,
(txtPhone) having three validators.
1.RangeValidator, 2.CustomValidator 3.Regexvalidator
Say,after validation (check what it returns if validation fails/passes) and act upon that.
if(rangevalidator1 != null)
{
...somecode...
}
I ll suggest you using javascript ..
you can use a single custom validator for all three validation and you put your code in if condition according to your need.
<asp:CustomValidator runat="server" ID="cstmStartDateValidater"
ToolTip="Start date cannot be greater than equal to end date/time or less than current date/time"
ErrorMessage="*" ControlToValidate="txtStartDateTime"
ForeColor="Red" ValidationGroup="vlgMessage" SetFocusOnError="true"
onservervalidate="cstmStartDateValidater_ServerValidate" ></asp:CustomValidator>
in the .cs page
protected void cstmStartDateValidater_ServerValidate(object source, ServerValidateEventArgs args)
{
if (CompareStartDate())
{
args.IsValid = true;
}
else
{
args.IsValid = false;
}
}
you can use following link for more information :
MSDN,
Code Project
hope these will help you .
Make use of ValidatorCalloutExtender control which is available in ajax control toolkit.
Place a separate ValidatorCalloutExtender across each control,you wish to validate it.
I'm trying to use the regular expression validator for a numeric ID field. The field needs to be a required field of any number. Currently, I'm using:
="\d{1,}"
Shouldn't this make it so the user has to at least enter 1 digit?? If I hit the submit button with the field empty, it passes validation and posts back.. But if I enter non-numeric characters, it errors fine. If I wanted zero or more occurrences, I'd use: ="(\d{1,})?"
Why isn't this working? Do I need to use this in combination with a Required Field Validator? That would suck ><
Make sure you set the property ValidateEmptyText to true or else the CustomValidator will not fire for empty text.
EDIT: You can attach a javascript function to the CustomValidator to accomplish this since I don't think a RegularExpressionValidator will fire against an empty control. I have created a basic example to illustrate the solution:
<script type="text/javascript">
function CheckMyText(sender, args) {
var compare = RegExp("\\d{1,}");
args.IsValid = compare.test(args.Value);
return;
}
</script>
<asp:TextBox ID="txtTest" runat="server"></asp:TextBox>
<asp:Button ID="btnTest" runat="server" Text="Test" />
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Error!"
ControlToValidate="txtTest" ValidateEmptyText="true"
ClientValidationFunction="CheckMyText"></asp:CustomValidator>
I have tested it and it seems to work. Leave a comment if you require further assistance.
You still need to use a RequiredFieldValidator.
I'm not sure where the user is entering the IDs, but if the input field is TextBox control why don't you use something like this:
if (tbID.Text.Length != 0)
{
//Logic goes here
}
When user clicks submit, you need to make sure that not only empty strings are captured, below is a regex that looks for any whitespace(tab,space etc) + matches if character is not a digit(0-9)
Dim FoundMatch As Boolean
Try
FoundMatch = Regex.IsMatch(SubjectString, "\Dm/rld$/\s", RegexOptions.IgnoreCase Or RegexOptions.Multiline)
'put your code here
Catch ex As ArgumentException
'syntax error in regular expression
End Try
I believe you'll need to use postback on your page, if you decide to use RequiredFieldValidator you can use above regex expression for that as well
Hth
In case someone is not using a CustomValidator then you can have a RequiredFieldValidator and RegularExpressionValidator for the same control. Found this solution here: http://forums.asp.net/t/1230931.aspx . Normally, this results in the error messages being displaced for the second validator but there is a way to fix that. You just have to set the Display property to dynamic for both the validators. Now the error messages for both the validators are displayed in the same location. Example code:
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
ErrorMessage="ErrorMsg" ControlToValidate="controlID"
ValidationExpression="regexExpression"
Display="Dynamic"></asp:RegularExpressionValidator>
<asp:RequiredFieldValidator ID="RequiredFieldValidator7" runat="server"
ErrorMessage="ErrorMsg" ControlToValidate="controlID"
Display="Dynamic"></asp:RequiredFieldValidator>`
I have some code where I need two separate required field validators for one control, both in separate validation groups which are then validated by two separate buttons.
This approach works well when the buttons are clicked but both validators show if I enter a value in the textbox and then remove it.
Is there a way to turn this"lost focus" validation off? I only need it to validate when the buttons are clicked.
EDIT
Unfortunately, if I set EnableClientScript=false then I dont have any client notifications. What I want is for the dynamic error message to show (effectivly in the OnClientClick event of the button) but not the "lost focus" of the textbox.
Is there some way I can disable or "unhook" the lostfocus client event?
EDIT
A combination dDejan's answer and womp's answeer here sorted the problem perfectly.
My final code looks like this (for anyone else with a similar situation)...
Javascript...
<script type="text/javascript">
$(document).ready(function() {
$('body').fadeIn(500);
//Turn off all validation = its switched on dynamically
$.each(Page_Validators, function(index, validator) {
ValidatorEnable(validator, false);
});
});
function ToggleValidators(GroupName) {
$.each(Page_Validators, function(index, validator) {
if (validator.validationGroup == GroupName) {
ValidatorEnable(validator, true);
} else {
ValidatorEnable(validator, false);
}
});
}
</script>
ASPX Control Example...
<telerik:RadTextBox Width="196px" ID="txtFirstName" runat="server" MaxLength="50" Skin="Black"></telerik:RadTextBox>
<asp:RequiredFieldValidator ID="valFirstName" CssClass="Validator" runat="server" EnableClientScript="true" Display="Dynamic" ErrorMessage="You must enter your first name." ControlToValidate="txtFirstName" ValidationGroup="NeededForEmail"></asp:RequiredFieldValidator>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" CssClass="Validator" runat="server" EnableClientScript="true" Display="Dynamic" ErrorMessage="You must enter your first name." ControlToValidate="txtFirstName" ValidationGroup="NeededForSubmit"></asp:RequiredFieldValidator>
ASPX Button Code...
<asp:Button ID="btnGetConfCode" runat="server" Text="Get Confirmation Code" OnClientClick="ToggleValidators('NeededForEmail')" OnClick="btnGetConfCode_Click" Width="100%" ValidationGroup="NeededForEmail"/>
<asp:Button ID="btnRegisterUser" runat="server" Text="Register" OnClientClick="ToggleValidators('NeededForSubmit')" OnClick="btnRegisterUser_Click" Width="100px" ValidationGroup="NeededForSubmit" />
So, now there is no validation until a user clicks either the "Get Email Confirmation Code" button or the "Register" button.
If they click the "Get Email Confirmation Code" button all of the controls validate apart from the textbox where the user is to input the email validation code and we only see one validator message.
If they click the "Register" Button then all of the controls validate and we only see one validation message.
If either button is pressed, the user goes back, adds and then removes some text then we only see one validator. Before this change you used to see both messages saying the same thing.
Thank you for help guys
You can set if the validators are "active" or not with client side code using the ValidatorEnable function. Basically it goes like this
var validator = document.getElementById('<%=Validator1.ClientID%>');
ValidatorEnable(validator , state); //where state is boolean
You can also trigger the validator to validate on some event (like for example the click of the buttons) using the ValidatorValidate(validator) function.
I am not sure which would work better for you (enabling/disabling the validators or custom triggering of the validation) but I suggest this article that will guide you in the right direction
ASP.NET Validation in Depth
There's no way to unhook them if EnableClientScript=true.
What you could do is set it to false. Then create a javascript validation method that is called on your submit-button onClientClick event.
In your method, you would have to call ValidatorValidate(control) for each control you want to validate client side
There's an example here:
http://msdn.microsoft.com/en-us/library/Aa479045#aspplusvalid_clientside
You could turn off the javascript validation by setting EnableClientScript="false" that would get rid of the lost focus validation.
You can use Custom Validator controls instead and either validate the input using Javascript on the client or within the event handler on the server. Ensure you set ValidateEmptyText="true" on the validation controls otherwise the events will not fire on an empty field.
Try to Enable on Both button click using javascript and disable it on textbox blur event.
Try resetting the onchange event for the input-control.
$(document).ready(function () {
$("#controlid").each(function () { this.onchange = null; })
});
var validator = document.getElementById('<%=Validator1.ClientID%>');
ValidatorEnable(validator , state);
It is working in javascript but when we use the page.Isvalid function on Server side it creates the problem to check page is valid or not.
simply type this code in page_load event
textboxname.Attributes.Add("onblur","ValidatorOnChange(event);");
Let's take the following simple site as an example:
<asp:TextBox id="TextBox1"
runat="server"></asp:TextBox>
<asp:RequiredFieldValidator
id="RequiredFieldValidator1" runat="server"
ErrorMessage="Required!"
ControlToValidate="TextBox1">
</asp:RequiredFieldValidator>
Now, I would want the TextBox1 to change its BackColor to yellow when ever the validation has failed. Is there a simple way to accomplish this?
Page.Validators is a ValidatorCollection. You can iterate this collection casting each member to BaseValidator. Check BaseValidator.IsValid and get the name of the control from BaseValidator.ControlToValidate. Use this.FindControl(control name) to get a reference to the control (this returns a Control object). Perform whatever type checking and casting you need to do, and then if you can cast the control to TextBox or some other control that contains the BackColor property, cast it and set the BackColor.
Here's a simplified version:
private void setInvalidControlsBackColor()
{
Control c;
TextBox t;
foreach (BaseValidator v in Page.Validators)
{
if (!v.IsValid)
{
c = (Control)this.FindControl(v.ControlToValidate);
// check the type, make sure you can cast this...
t = (TextBox)c;
t.BackColor = Color.Yellow;
// or however else you want to handle this...
}
}
}
The reason I didn't include code for the type checking stuff is because you may want to handle the different control types differently, etc. Also, if you're not using the ToolTip fields on your validators, you can use this field to store additional info (kind of like the Tag property). That might be considered ugly practice, but it's there for you if you need it...can be used as a hint of what to do with valid/invalid states.
A better option would be to inherit from the system validators and create your own validators. You can override the default behavior to change the background color of the ControlToValidate field. For most controls you don't need to check the type, you can just set the style value to "background-color:yellow".