I have an ASP.NET web app (with C#). In it I have a form with several fields and validators. For one of the validators I only need to validate when:
a certain textbox is empty
and a certain record does not exist in the database (this is already handled).
I know I can't enable/disable the validator on page_load because something might be entered into that textbox. I also tried the following in the onclick event of the submit button but it didn't seem to work:
Validator1.Enabled = true;
Validator1.Validate();
I also tried Page.Validate() but that didn't work either...
Can anyone please help?
Thanks
Use a customvalidator. Inside the Validation Event you have code like this pseudo code:
OnValidating(object sender, ServerValidateEventArgs e)
{
if(CertainTextBox.Text.IsNullOrEmpty() && CertainRecordDoesNotExistInDB))
{
// validate
// and set e.Valid to the desired validation output
}
else
{
e.IsValid = false;
}
}
this things should be done by JavaScript on client. Then on submit you should validate at server side.
Related
I have a textbox in which user enters the jobnumber. I am checking if this number exists in the database, by using a server side CustomValidator. I want this CustomValidator to be called before anything else in the page. Right now it is firing the CustomValidator only if all the RequiredFieldValidators are validated to true. And the validation is happening on button click.
Is it possible to validate CustomValidator before the other RequiredFieldValidators? Also, is there a way in which, as soon as the jobnumber is entered into the textbox, we can validate the number and display an error if it is invalid, immediately and not wait until the button click?
If you're using a CustomValidator, then set the ValidateEmptyText property to true and add code to your validation method to check if the value is populated. Then you don't need the RequiredFieldValidator at all. Just make sure you have a JavaScript function to do the validation client-side and set the ClientValidationFunction property.
To trigger the validation whenever you want , you can use the method described here (although I've never tried it): http://fczaja.blogspot.ca/2009/07/aspnet-how-to-trigger-client-side.html
function Validate()
{
// Get the specific validator element
var validator = document.getElementById('RequiredFieldValidator1');
// Validate chosen validator
ValidatorValidate(validator);
// Update validation summary for chosen validation group
ValidatorUpdateIsValid();
ValidationSummaryOnSubmit(validationGroup);
}
Then you can use that in the keypress event of the textbox.
I have a page with a textbox control, a Custom Validator, a button to save entered data and code to handle the custom validation.
I set up a simple code test just to see how the Custom Validators work.
I hope to add more validations that check multiple controls later. The same thing happens if I do add the ControlToValidate attribute for the textbox control.
(I don't think I need a "ControlToValidate" attribute for this. I plan to validate multiple controls later. I can't put all the controls I am validating in that attribute.)
When I run my app, the save takes place and the validation is happeing - the message appears. I don't understand why the save isn't stopped when I enter "3" in the textbox I am checking. If the validation is happening, and if the IsValid = false, why is the save taking place?
Here is the Custom Validator:
<asp:CustomValidator ID="VisitSaveCustomValidator" runat="server" OnServerValidate="VisitSaveCustomValidator_ServerValidate" ValidationGroup="SaveVisit_val"></asp:CustomValidator>
Here is the button:
<asp:Button ID="SaveVisit_btn" runat="server" Visible="false" Text="- Save Visit -" ValidationGroup="SaveVisit_val" OnClick="SaveVisit_btn_Click" />
Here is the code for the Custom Validator:
protected void VisitSaveCustomValidator_ServerValidate(object source, ServerValidateEventArgs args)
{
if (VisitNumber_tbx.Text == "3")
{
args.IsValid = false;
VisitSaveCustomValidator.ErrorMessage = "The Visit Number cannot be 3.";
}
else
{
args.IsValid = true;
}
Please let me know if I need to add more code or more information.
I thought this would be pretty straight-forward. I followed an example in a book and some online. I understand that the page is going back to the server to be validated. But, shouldn't the save be stopped since the IsValid = false?
It seems like the save is happening first, then the validation code executes, which causes the message to appear.
Thanks.
I believe you may have to manually call the validate method.
VisitSaveCustomValidator.Validate();
Then check to see if it was valid.
VisitSaveCustomValidator.IsValid();
This can be put in the button click event.
I've put a CustomValidator on my form. I have not set its ControlToValidate property. In its ServerValidate event I've written the following:
protected void CustomValidator1_ServerValidate(object source,
ServerValidateEventArgs args)
{
args.IsValid = false;
}
I put a breakpoint to this method but it seems to never come to that point. But if I do this on another form it works like a charm.
The ValidationGroup property of both the button and the CustomValidator are the same
I tried deleting this property in both the button and the CustomValidator, still does not work.
It seems as there's something formwide. I just put a CustomValidator on the form and do not touch any of its properties other than just setting its ServerValidate event method.
EDIT: Here's the aspx part:
<asp:CustomValidator ID="CustomValidator2" runat="server"
ErrorMessage="This is a test"
onservervalidate="CustomValidator1_ServerValidate"
ValidationGroup="PA"></asp:CustomValidator>
<asp:Button ID="btnPensionersOK" runat="server" Text="OK" Width="75px"
onclick="Button1_Click" ValidationGroup="PA" />
Try to force the validation in the button-click handler via Page.Validate:
protected void Button1_Click(Object sender, EventArgs e)
{
Page.Validate();
if(Page.IsValid)
{
// servervalidate should have been called
}
}
Edit(from comments):
If you want the customvalidator to validate if nothing was entered/selected in your controls, you need to set ValidateEmptyText to true. You also might want to let the CustomValidator replace the RequiredFieldValidators.
I assume that the validator-order on the aspx decides whether or not a customvalidator's severvalidate is called if a previous Validator already has made Page.IsValid=false. Or ASP.NET is so smart that it assumes the SeverValidate to be costlier than a simple text-is-empty check.
I would also like to put some more help for those who will use CustomValidators and RequiredFieldValidators at the same time. One should take into account that Client side validation takes place first. And the server side validation will occur only after PostBack. I'm sure you got it but just in case this is not quite clear: It means first all the controls that are bound to certain client side working validators must be valid to let Postback to occur. After Page. IsValid is True server side stuff takes place and posts back any changes which includes server side validation messages.
So here are the ways one can make both CustomVCalidators and other built in validators to work at the same time.:
Set both groups of validators to work on Client side. In this case we must ensure that for the custom valitor(s) we spacify the script that will make validation on the client side. Without writing script and just filling in the ServerValidate method the validation will take place in the server.Even if EnableClientScript property is set to True.
Set both groups of validators to work on server side. To do so simply set EnableClientScript to False. But note that this will load the server.
I have an asp.net page with multiple validation summaries setup with ShowMessageBox="True" and several validators. I have run into a situation where when validation fails the validation summary displays correctly but then the next click that would normally trigger a postback of the page does not trigger a postback. So the steps look like this:
Click button that triggers validation.
Validation fails and a messagebox with the failure message is displayed.
Click a different button which does not validate but should trigger a postback nothing happens
Click same button as step 3 again postback happens as expected.
What could cause this behavior?
EDIT: The validation was being done in the following manner. In the asp page:
<asp:Button runat="server" id="btn" onClientClick="return DoValidation();" />
In the javascript:
function DoValidation() {
if (!Page_ClientValidate('group1'))
return false;
if (!Page_ClientValidate('group2'))
return false;
return true;
}
After working on this and making careful use of the debugger I finally found out that when you do validation the way described in the edit to the question a boolean is set on failure that blocks the next PostBack of the page from going through. I believe this is done when validation is being done automatically instead of explicitly as I'm doing here. Changing the javascript described above to look like this:
function DoValidation() {
if (!Page_ClientValidate('group1')) {
Page_BlockSubmit = false;
return false;
}
if (!Page_ClientValidate('group2')) {
Page_BlockSubmit = false;
return false;
}
return true;
}
Causes the problem to go away. Hopefully this will help the next person who makes the same mistake I did.
i have a validationSummary in my page. i want to call a javascript function after the validationSummary is filled. how can i achieve this?
i think i should add an attribute in the code behind, but i can't figure out what is the attribute's key.
any help?
You will want to call the javascript function Page_ClientValidate() to initiate the ASP.NET validation wired to your page controls. Once this is called, the Page_IsValid boolean value will be properly set.
Here is an example of how I am using it. If ASP.NET validation is successful, I disable the button, otherwise the button remains enabled and the validation summary is displayed to the user. The OnClientClick is from a ASP:Button control.
OnClientClick="javascript:Page_ClientValidate(); if (Page_IsValid==true) { this.disabled=true; }"
I don't think that's possible. It is, however, possible to intercept validation by setting OnClientClick on the controls that do postbacks. Then you can check the global JavaScript variable Page_IsValid for the validation result.
One thing to keep in mind is that, when there are no validators on a page, Page_IsValid will be undefined.
I started to implement the solution by #EverettEvola but also where the validation logic was being called multiple times and displaying multiple ValidationSummary popups. My solution was as follows:
On the button (in my case the button was a submit button)
OnClientClick="return CustomValidationOnClick()"
And the CustomValidationOnClick()
function CustomValidationOnClick(source, args) {
//Manually kickoff page validation
//This call will display the Validation summary popup if page is invalid
Page_ClientValidate();
//Page_IsValid set by the result of the Page_ClientValidate() call
if (Page_IsValid == true) {
this.disabled=true;
return true; //if Submit button return true to continue form submit
}
else {
//do whatever here
return false; //if Submit button return false to cancel form submit
}
}