I have 2 TextBoxes (textBoxA, textBoxB), both watched by their own RequiredFieldValidator. I want to 'enable' the RequiredFieldValidator for textBoxB just when textBoxA has a value (or meets some specific conditions).
Use cases:
Case 1
textBoxA = ""; -> Show Required Field Validation Message
textBoxB = ""; -> Do not show validation message
Case 2
textBoxA = "has a value";
textBoxB = ""; -> Show Required Field Validation Message
Case 3
textBoxA = "has a value";
textBoxB = "has a value too";
Thanks for your help!!
You might want to use a CustomValidator to do this. You'll need to implement the client side and server side validation. Something like (off the top of my head and untested)
Server side
protected void ServerValidation (object source, ServerValidateEventArgs args)
{
if (!string.IsNullOrEmpty(textBoxA))
args.IsValid = !string.IsNullOrEmpty(textBoxB);
}
Client Side
function clientValidation(sender, args) {
if (args.value !== "") {
var textBoxB= document.getElementById('textBoxB');
args.IsValid = (textBoxB.value !== "");
}
return;
}
In this situation I'd use a CustomValidator for textBoxB instead of the required field validator. In the server side validation method you can control the exact nature of the validation with something like this.
if (textBoxA.Text != string.Empty)
{
args.IsValid = textBoxB.Text != string.Empty;
}
I don't believe there's a declarative way to do it. I've always done this by having a ValidatePage method where I set my validators to enabled or disabled and then call Page.Validate at the end (and then proceed or render based on Page.IsValid).
So, either
validator2.IsEnabled = textBoxA.Text.Trim().Length > 0
or something like that.
That's pseudo code btw...I haven't done ASP.NET in some time now.
What I do is to change the Validation Group according to requirement, for example, you may assign the validation group to the textBoxB to a value different or the same that textBoxA.ValidationGroup & the submit control, this may be done in textBoxB's Onchange.
Validators which are evaluated are all that correspond to the same validation group of the submit control.
Related
I have an aspx page with three textbox controls, and i want to do validation for all.
i want to show the error message in a sequence,
for example if i left all three text boxes empty and click on submit button,
first it will show error message for first text box and then when i fill the first textbox and click again save then it shows the error message for the second textbox and so on.
that means i only want to show one error message at a time after clicking the submit button.
can you people suggest me the way.
You could do it though checking on submission of the form and posting back to a literal with error messages. Postback validation is better than just relying on javascript in any case.
So, depending on the level of checks you want to employ, you could do something like:
protected void btnSubmit_Click(object sender, eventArgs e)
{
if(String.IsNullOrEmpty(txtBox1.Text))
{
ltError.Text = "Sorry, error message for box1";
return;
}
}
Obviously you'd work in more checks and after passing stage1 you'd move on to stage 2. Not great from a user experience but would work.
you can return a function value like this
public string CheckValidation()
{
if (txtFirstName.Text.Trim().Equals(string.Empty))
return "Please enter firstname";
if (txtLastName.Text.Trim().Equals(string.Empty))
return "Please enter lastname";
}
and so on as per your validation fields.
Hope this helps you
Can you use the AJAX control toolkit? The VaidatorCallout controls behave this way and you get a nice little balloon indicating where the error is.
ASP.NET Validator Callout
I'd recommend an <asp:CustomValidator> control for each textbox. You can use something like the following for the custom validation routines:
var textBox1IsValid = function textBox1IsValid(sender, args) {
var tb = document.getElementById('TextBox1'),
resultOfValidation = false;
//do validation, modifying resultOfValidation as needed.
arg.IsValid = resultOfValidation;
return resultOfValidation;
},
textBox2IsValid = function textBox2IsValid(sender, args) {
var tb = document.getElementById('TextBox2'),
resultOfValidation = false;
//do validation, modifying resultOfValidation as needed.
//return either the validity of TextBox2
//or (if TextBox1 is not valid) return true so the
//validator for TextBox2 doesn't fire.
arg.IsValid = resultOfValidation || !textBox1IsValid(sender, args);
return resultOfValidation;
},
textBox3IsValid = function textBox3IsValid(sender, args) {
var tb = document.getElementById('TextBox3'),
resultOfValidation = false;
//do validation, modifying resultOfValidation as needed.
//return either the validity of TextBox3
//or (if either TextBox1 or TextBox2 is not valid) return
//true so the validator for TextBox3 doesn't fire.
arg.IsValid = resultOfValidation || !textBox1IsValid(sender, args) || !textBox2IsValid(sender, args);
return resultOfValidation;
};
The advantage of this approach is that TextBox2 and TextBox3 will return as valid if their contents are valid or if TextBox1 is not valid. This will fire only one validator at a time, until all fields are valid. It's also a little more flexible as your custom validation routine can check for:
required field
pattern matching
value comparison
or any other validation that you need, all wrapped up into one function.
The downside is that you'll also need to duplicate the validation logic server-side.
Don't know what is wrong here. This is a page developed by someone else and I am trying to fix one of the issue.
Scenario:
ASP.NET site.
Login.aspx has <asp:login> and there are three validation groups.
Login.aspx.cs is a partial class of "user_login".
Each validation group has a textbox and an associate customvalidator. All three custom validators gets triggered when something is entered in corresponding textbox but issue is only the first textbox (bound to validationgroup = 1) returns false when validation fails.
For 2nd and 3rd, the customvalidator get triggered but when there is validation issue and even after setting "args.IsValid = false;", the process continues with what needs to be executed further.
Don't know what is going on wrong here. I would like the customvalidator to return false. Worst case, are there any ways to return the control back to the 'textbox' when validation fails?
Below is the custom validator used.
<asp:CustomValidator ID="ExistingIdValidator" runat="server" ControlToValidate="NewUserName"
ValidateEmptyText="true" ValidationGroup="NewUserForm"
OnServerValidate="NewUserNameCheck_ServerValidate">
</asp:CustomValidator>
protected void NewUserNameCheck_ServerValidate(object source, ServerValidateEventArgs args)
{
CustomValidator validator = source as CustomValidator;
if (validator != null)
{
string NewuserNameValue = this.NewUserName.Text;
Guid registeredUserId = (Guid)Membership.GetUser(NewuserNameValue).ProviderUserKey;
if (registeredUserId != null)
{
validator.IsValid = false;
this.FailureText_New.Text = "This UserID already exists. Please login as existing user";
args.IsValid = false;
}
}
}
The funny thing about ASP.NET server-side validation is that it does not automatically prevent your click events from executing. It's as if the validation procedure is performed and then the results are ignored. So, the first thing to put inside your button's event is if (!Page.IsValid) return;. That's how you prevent the rest of the event from executing, and that's how you force the user to correct any mistakes on the form.
The current form is here. It is not complete, and only a couple options will work.
Select "Image CD" and then any resolution and click "Add to Order." The order will be recorded on the server-side, but on the client-side I need to reset the product drop-down to "{select}" so that the user will know that they need to select another product. This is consistant with the idea that the sub-selections disappear.
I don't know whether I should be using ASP postback or standard form submittal, and most of the fields need to be reset when the user adds an item to the order.
I'd use Response.Redirect(Request.RawUrl) method to reset the form data from the server side.
A little explanation: this is PRG design pattern
Used to help avoid certain duplicate
form submissions and allow user agents
to behave more intuitively with
bookmarks and the refresh button.
A workaround for this question:
necessary data may be stored in Session for example. This means we getting the data with the first POST, putting it to the storage, performing redirect and getting it back.
In the pageload event on the form, you need to add something simalar to this:
if (IsPostBack)
{
//Proccess the order here
ProductOption.SelectedIndex = 0;
}
That will allow you to process the order, but then start over the order form.
The simplest means would be a recursive function that forks on the type of control
private void ResetControls( Control control )
{
if ( control == null)
return;
var textbox = control As TextBox;
if ( textbox != null )
textbox.Text = string.Empty;
var dropdownlist = control as DropDownList;
if ( dropdownlist != null )
dropdownlist.SelectedIndex = 0; // or -1
...
foreach( var childControl in controlControls )
ResetControls( childControl );
}
You would this call this function in your Load event by passing this. (This is presuming you want to reset more than a single control or small list of controls).
I have a CustomValidator that is validating a telephone number for several different telephone numbering schemes. The client-side javascript looks like this:
validatePhoneNumber(sender, args) {
cleanNumber = args.Value.replace(/\D/, "");
country = $("#" + CountryID).get(0).value;
switch (country) {
case "North America":
args.IsValid = validateNAPhoneNumber(cleanNumber);
if (!args.IsValid) sender.errormessage = "* Not a NA Phone #";
break;
case "UK":
args.IsValid = validateUKPhoneNumber(cleanumber);
if (!args.IsValid) sender.errormessage = "* Not a UK Phone #";
break;
...
}
}
The actual validation takes place properly, and the CustomValidator has the correct IsValid property at all times. The sender.errormessage, however, seems to be rewritten just after this function call to it's default value. How can I change the errormessage value, and make it "stick"?
function dateofbirth(sender, args) {
var dtcDOB = document.getElementById('<%= dtcDOB.ClientID %>');
var dob = new Date(dtcDOB.value);
var currDate = new Date();
if (dtcDOB.value == "") {
args.IsValid = false;
sender.textContent = "Provide DOB.";
return;
}
args.IsValid = true;
}
Try sender.textContent = "your err msg".
It worked for me.
The best way to change the error message of a validator control with image is:
sender.innerHTML = "YOUR HTML WITH ANYTHING COME HERE"
To change the error message, do it like this:
if (!args.IsValid) document.getElementById('<%= cstPhoneNumber.ClientID %>').errormessage = "* Not a NA Phone #";
To change the text, do this:
if (!args.IsValid) document.getElementById('<%= cstPhoneNumber.ClientID %>').innerHTML = "* Not a NA Phone #";
cstPhoneNumber should be replaced by the name of your validation control.
It looks like your using jquery so you could set the error message like this:
$(sender).text("* Not a NA Phone #");
Edit:
Sorry for the delay but I was away on vacation.
I was playing a round with a simple page and I think I understand how this works.
When you set the errormessage on the sender in the client side validation function you are setting the equivalent of the ErrorMessage property.
This is different from the Text property. The ErrorMessage sets the text displayed in the Validation summary, while the Text property is the text displayed in the validator control. Note that if you only set the ErrorMessage property (on the server) then the ErrorMessage will be copied into the Text property.
What this means is that when you set sender.errormessage your actually setting the text that is displayed in the validation summary.
Hopefully this will help clear it up. However, I still haven't seen a way to change the Text property from the client side validation function. I am also not sure why your sender object is not the validator object.
sender.innerText = "Your message" will work.
I think the problem is that there is no 'errormessage' property on the client side. The custom validator renders a <span> tag to display the error message with an id corresponding the id property of the custom validator control. To set the text displayed when validation fails you need to do somthing like this.
...
case "North America":
args.IsValid = validateNAPhoneNumber(cleanNumber);
if (!args.IsValid)
document.getElementById(sender.id).innerText = "* Not a NA Phone #";
break;
...
Just remove all instances of Text and ErrorMessage in the custom validator tag definitions
then use
$(#id_of_custom_validation_control).text("custom error message");
Then with this, you can use one custom validator control and handle multiple error conditions
E.g
if(error1){
$(#id_of_custom_validation_control).text("custom error message1");
}else $(#id_of_custom_validation_control).text("custom error message2");
Hope this helps
Expanding #Andy response, using jQuery:
Change the text message (show in the form):
$('#<%=this.[Validator].ClientID%>').text('Text to show');
Change the error message (for the Summary control):
$('#<%=this.[Validator].ClientID%>').attr('errormessage', 'Text to show');
Replace [Validator] for your validator's name.
Try this...
Use sender.textContext in the Javascript for the error message and setup your CustomValidator as such:
<asp:CustomValidator ID="cvdPhoneNumber" runat="server" Display="Dynamic" ForeColor="Red" ControlToValidate="txtPhoneNumber" ClientValidationFunction="validatePhoneNumber" ErrorMessage="" />
Right now i have an asp.net 2.0 app which allows a user to search by the following fields
Location (Required if there is nothing in idnumber field)
Address (Required if there is nothing in idnumber field)
Zip (Required if there is nothing in idnumber field)
**OR**
IDNumber. (Required if there is nothing in any of the other fields)
What i'd like to be able to do is validate this client side on button click and display a summary of errors.
i.e.
if a user leaves every criteria blank. I'd like to display "You must enter a IDNumber or "Location, Address, and Zip to continue"
I've never used the Custom Validation control so here are some questions.
1) Is it able to do this?
2) Does anyone have an example of how to do this?
Thanks
You can use the ClientValidationFunction property of a CustomValidator control to specify a Javascript function that will validate your form. You'll need to write the JavaScript for the validation. Unless you're writing an application where you can be absolutely sure that all of your clients have JavaScript enabled, I highly recommend you also use the OnServerValidate property to also provide server-side validation.
Server-side CustomValidator example: https://web.archive.org/web/20211020145934/https://www.4guysfromrolla.com/articles/073102-1.aspx
Client-side example: http://www.codeproject.com/KB/custom-controls/CustomValidatorAndSummary.aspx
It is fairly simple to use a custom validator. Add one to your page, and choose the ServerValidate event, which will generate a function like this (example in C#):
protected void CustomValidator1_ServerValidate(object source,
ServerValidateEventArgs args)
{
// Your validation logic goes here... set args.IsValid = true if it passes,
// false otherwise. Here is an example...
args.IsValid = false;
if(txtIDNumber.Text.Length > 0)
{
args.IsValid = true;
}
else if (txtLocation.Text.Length > 0
&& txtAddress.Text.Length > 0
&& txtZip.Text.Length > 0)
{
args.IsValid = true;
}
}