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.
Related
I'm having an odd problem in that one of the 4 custom validators on my web page is not firing. Everything looks correct based on the working validators. Below is the simplified code.
ASPX code -
<asp:TextBox ID="CMT_TXT" runat="server" Columns="60" Rows="8"
TextMode="MultiLine" Text='<%#Eval("CMT_TXT")%>'></asp:TextBox><br />
<asp:CustomValidator ID="csvCMT_TXT" runat="server" ControlToValidate="CMT_TXT"
Display="Dynamic" EnableClientScript="False" ErrorMessage="Msg">
</asp:CustomValidator>
VB code -
Public Sub csvCMT_TXT_ServerValidate(source As Object,
args As ServerValidateEventArgs) _
Handles csvCMT_TXT.ServerValidate
dim s As String = CMT_TXT.Text
args.IsValid = s.Length <= 3500
End Sub
When testing,
The contents of field CMT_TXT has approximately 3000 characters. So it is not an empty field issue.
Page.Validate is called in the main body of the code
for server side validation to fire you need to call Page.Validate, this should trigger all your server side validation and update Page.IsValid
Also it does not look like you have the event set up on the custom val. may want to add the prop OnServerValidate
OnServerValidate="csvCMT_TXT_ServerValidate"
<asp:CustomValidator ID="csvCMT_TXT" runat="server" ControlToValidate="CMT_TXT"
Display="Dynamic" EnableClientScript="False" ErrorMessage="Msg" OnServerValidate="csvCMT_TXT_ServerValidate">
</asp:CustomValidator>
I'm not too familiar with VB.NET, but with C# I'll check the Page.IsValid field before continuing on with a page that has a CustomValidator.
An example with a Wizard control that contains a CustomValidator in the final stage, I will check this value in the FinishButtonClick event.
protected void Wizard1_FinishButtonClick(object sender, WizardNavigationEventArgs e)
{
if (Page.IsValid == false)
{
// validator failed, stop wizard from continuing
return;
}
// page is valid, continue on
// ...
}
Not sure if there are any differences with VB.NET, but may be worth a shot
At a glance, it looks like you named your handler incorrectly. The control ID is csvCMT_TXT while the handler is csv_CMT_TXT.ServerValidate. There's an extra _ in the handler.
The problem turned out to be a problem with the VS2010 project build.
To this the problem, I had to
Deleted all files in BIN directory
Deleted all file in OBJ directory
Deleted Custom Validator
Rebuilt the Project
Add Custom Validation back into program. Added the original code back into program
It's a bit extreme, but this is what it took to resolve the problem.
I am not too familiar with custom validation. If you are willing to help, it is MUCH appreciated!
<asp:CustomValidator ID="valMatchUserInput" runat="server" ControlToValidate="tbUserInput" ErrorMessage="Please do something."> </asp:CustomValidator>
Basically, if the user input does not match (is not equal to) a specific parameter, I would like an error message to display, so nothing happens until the user fixes the error.
Thanks!
I will give you an example...
Let's say this is your validator:
<asp:CustomValidator ID="valMatchUserInput" runat="server" ControlToValidate="tbUserInput" ErrorMessage="Please do something." **ClientValidationFunction="Bla_ClientValidate" OnServerValidate="Bla_ServerValidate"**> </asp:CustomValidator>
You have to include a server-side validation and a client-side validation.
Code behind (server-side)
protected void Bla_ServerValidate(object source, ServerValidateEventArgs args)
{
//Compare your parameter here
}
Javascript (client-side)
function bla_ClientValidate(sender, e) {
// Compare your parameter here
}
It should work then
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);");
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.