Stop Postback in Image Button after validation failed - asp.net

I have a aspx page containing a text box and an image button for search. I have used compare validator (to check for integer values) with the textbox. But the page reloads on the image button click even if I enter alphanumeric characters, along with showing the error message.
I tried using a regularexpressionvalidator instead but the problem persists.
But when i used a simple asp:button instead and binded it with textbox validation, its working fine (i.e. postback does not occur on incorrect value of textbox) and same is true with dropdownlist also (no postback occuring).
Please suggest.
Here's the code-
#peroija : Here's the code
<asp:ImageButton ID="btnSearch" runat="server" OnClick="btnSearch_Click"
ToolTip="Search" ValidationGroup="valControl" CausesValidation="true" />
<asp:TextBox ID="txtWidth" CssClass="TextFont" runat="server"
Width="233px" MaxLength="20"
ValidationGroup="valControl" CausesValidation="true"></asp:TextBox>
<asp:CompareValidator runat="server" ID="cmpValWidth"
ErrorMessage="Please enter integer values" ControlToValidate="txtWidth" Display="Dynamic"
Operator="DataTypeCheck" ValidationGroup="valControl"Type="Integer"/>

Sounds to me like you need to write
if(!isPostBack)
{
"your code"
}
in the code behind. To prevent the code from being run if the page is not viewed for the first time

Remove this from your textbox, you only need it on the validator and the button:
ValidationGroup="valControl" CausesValidation="true"
If javascript is disabled, then there will be no client side validation, so always check the validity on the server side also:
if(Page.IsValid)
{
"your btnSearch_Click code"
}

Related

Why is DefaultButton not working?

I have the following code:
<form id="frmLogOn" runat="server" DefaultButton="testbutton">
<asp:Panel runat="server" ID="testpanel" DefaultButton="testbutton">
<asp:TextBox runat="server"></asp:TextBox>
<asp:Button runat="server" ID="testbutton" OnClick="dotest" UseSubmitBehavior="True"/>
</asp:Panel>
</form>
If I click the button, the page does a postback and calls dotest(), as expected.
If I press the enter key while focused on the textbox nothing happens.
I have investigated, and found that WebForm_FireDefaultButton(event, target) is being called when I type a different key (for example a letter or a number) but it is NOT being called when I press the enter key.
(Note I found it is called twice, and this is probably because I set the same DefaultButton for both the form and the panel).
Why is it not being called?
After some searching I determined this was caused by the following in my master page:
<body onkeydown = "return (event.keyCode!=13)" >
Works fine without it.

Multiple validation groups, only validate one on control blur

Summary
I have a single control with two (almost) identical validators, each linked to two validation groups. When the cursor leaves the control, both validators are automatically checked by ASP.NET. Is there a way to only fire one (without setting EnableClientScript="false") so there are not two * symbols being displayed on the blur?
Details
I have a form with two buttons asp:btnSave and asp:btnSubmit... both buttons require validation, as certain controls must be validated on the save for it to work correctly.
So I have two validation groups, the "default" group for submitting (i.e. ValidationGroup property is NOT set), and the "SaveGroup" for saving. There are two asp:ValidationSummary controls to reflect these.
On a single control that is (for example) designed to accept a decimal value, I have the following. Firstly a required field for the submit, then a range validator for the submit. Then a 3rd validator which is a replication of the range validator but is part of the "SaveGroup"...
<asp:TextBox runat="server" id="txtMyDecVal" />
<asp:RequiredFieldValidator runat="server" ControlToValidate="txtMyDecVal"
Text="*" ErrorMessage="Enter a value" />
<asp:RangeValidator runat="server" ControlToValidate="txtMyDecVal" Type="Double"
MinimumValue="0" MaximumValue="999.99" Text="*"
ErrorMessage="Value must be between 0 and 999.99" />
<asp:RangeValidator runat="server" ControlToValidate="txtMyDecVal" Type="Double"
MinimumValue="0" MaximumValue="999.99" Text="*"
ErrorMessage="Value must be between 0 and 999.99"
ValidationGroup="SaveGroup" />
This is working fine, and the two buttons validate correctly.
The problem is... there is a visual issue that if you type invalid text into the control, BOTH the RangeValidators are fired automatically by ASP.NET when the cursor leaves the control, resulting in two * symbols appearing.
Is there a way to make it so that only one of those validators are checked as part of the blur event on the control?
I could set EnableClientScript="false" on one of the validators, but I still want it to check the control on the client side without a post-back first.
Update
I have been playing with setting EnableClientScript="false" as I decided that the post-back on the save wasn't actually going to be a big issue.
However, this then leads on to another visual issue: Enter invalid text, the "submit" validator shows the *. Click the save, which posts-back and then displays the * for the "save" validator. If you then change the text to valid text, the "save" validator doesn't disappear, so it still looks like there's a problem... and if you change the text to different invalid text, you get the "submit" * appearing as well, resulting in the same as before... i.e. two * symbols.
You should add Display="Dynamic" to your validators.
<asp:RequiredFieldValidator runat="server" ControlToValidate="txtMyDecVal"
Text="*" ErrorMessage="Enter a value" Display="Dynamic" />
<asp:RangeValidator runat="server" ControlToValidate="txtMyDecVal" Type="Double"
MinimumValue="0" MaximumValue="999.99" Text="*"
ErrorMessage="Value must be between 0 and 999.99" Display="Dynamic" />
<asp:RangeValidator runat="server" ControlToValidate="txtMyDecVal" Type="Double"
MinimumValue="0" MaximumValue="999.99" Text="*"
ErrorMessage="Value must be between 0 and 999.99"
ValidationGroup="SaveGroup" Display="Dynamic"/>
Courtesy of Satheesh babu's artice, and having toyed with a couple of options -- I think the best way to deal with complex situations is to DIY.
I've set CausesValidation="False" and removed ValidationGroups from buttons, and put something like:
OnClientClick="if (EnableVal(['ValidationGroup1','ValidationGroup2']) == false) {return false;}"
for client-side validations, where particular buttons validate increasingly complex rules as the process moves ahead. This allows me to reduce duplicating validators.
Then, on server-side, I am calling Page.Validate("ValidationGroup#") for each group, depending on the buttons or even business process state, and then finally checking Page.IsValid.
Also, depending on the business process state, the buttons' OnClientClicks can be set from code-behind depending on which validation groups I want to deal with right now.
Finally, to combine validation summaries, see the javascript here: Page_ClientValidate() with multiple ValidationGroups - how to show multiple summaries simultaneously? (with some tweaks).
Net very elegant, but probably gives the most control.
I am faced with this issue too - I have:
Multiple ValidationGroups triggered by different buttons
Validations that need to take place in both groups (in my case RequiredFieldValidators)
Adding multiple validators works as above until you enter and then subsequently blank out a field - you get both messages. My workaround is as follows:
Overwrite the IsValidationGroupMatch JavaScript method to allow for comma seperated values in the ValidationGroup property:
function IsValidationGroupMatch(control, validationGroup) {
if ((typeof (validationGroup) == "undefined") || (validationGroup == null)) {
return true;
}
var controlGroup = "";
if (typeof (control.validationGroup) == "string") {
controlGroup = control.validationGroup;
}
//return (controlGroup == validationGroup);
var controlValidationGroups = controlGroup.split(",");
return (controlValidationGroups.indexOf(validationGroup) > -1);
}
Then in the ASP you add:
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ControlToValidate="TextBox1" ValidationGroup="VG1,VG2" Display="Dynamic">
Text box is required
</asp:RequiredFieldValidator>
<asp:Button ID="Button1" runat="server" Text="Validate VG1"
OnClick="Button1_Click" ValidationGroup="VG1" />
<asp:Button ID="Button2" runat="server" Text="Validate VG2"
OnClick="Button2_Click" ValidationGroup="VG2" />
This works on the client, but on the server you would need to add custom line(s) of code to ensure the controls listed as needing to be validated by both are checked:
// controls listed as part of ValidationGroup 'VG1' will have had their
// validation tested, ones listed as 'VG1,VG2', 'VG2,VG1' etc would not
protected void Button1_Click(object sender, EventArgs e)
{
Page.Validate("VG1,VG2");
if (!Page.IsValid)
return;
// do something
}
This way the validation controls are only needed to be added once but can be implemented for multiple ValidationGroups. It's really only a workaround/hack that works on the client, the extra checks on the all-important server side validation will need to be done manually each time.

ASP.NET Required Field Validator not working

Hi all I need a required field validator for my textbox..This is my textbox..
<asp:TextBox ID="txtTimeSlotGroupName" runat="server" AutoPostBack="false"
ClientIDMode="Static"></asp:TextBox>
<font color="red">*</font>
<asp:RequiredFieldValidator ID="RequiredFieldValidator_txtTimeSlotGroupName"
runat="server" ControlToValidate="txtTimeSlotGroupName" Display="None"
ErrorMessage="Timeslot Group Required!" ForeColor="Red" InitialValue="0"
ValidationGroup="TimeSlot"></asp:RequiredFieldValidator>
My button:
<asp:Button ID="btnAddTimeSlots" Text="Add Timeslots" CssClass="button"
runat="server" OnClick="btnAddTimeslots_Click" ValidationGroup="TimeSlot"
OnClientClick="javascript:shouldsubmit=true;"/>
I am not getting the error message. Any solutions?
You have to define the Validation Group Of your Textbox too....to make it work
<asp:TextBox ID="txtTimeSlotGroupName" runat="server"
AutoPostBack="false" ValidationGroup="TimeSlot" ClientIDMode="Static"></asp:TextBox>
Remove InitialValue="0" from the RequiredFieldValidator tag, it is not required when you are validating the textbox.
Even I was facing the same issue. Kindly check if any javascript are present on your page. Irrespective of above make use of Page.Validate() method and if(Page.IsValid) in your code. This will automatically force your validation controls and issue will be solved
If two objects have the same id the required field validator Does not work.
You just add ValidationGroup="TimeSlot" in textbox
<asp:TextBox ID="txtTimeSlotGroupName" runat="server" AutoPostBack="false"
ValidationGroup="TimeSlot" ClientIDMode="Static"></asp:TextBox>
I had this same issue... but none of the above answers were the fix for me...
My problem was that I was missing the Page.isValid in my button press method. Below is my button code and the method called by the button.
Button:
<asp:Button ID="btnBtmSave" runat="server" Text="Save" OnClick="btnSave_Click" BtnGroup="save" TabIndex="18" />
Button method:
protected void btnSave_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
//Logic goes here
}
}
make the same Validation Group Of all your text and Add button and Validation
ValidationGroup="AAA"
and add the code to your save button:
If (Page.IsValid) Then
YOURSQL.Insert()
'or ur code here'
End If
In my case, For button, I was using both client side validation i.e onClientClick="return validate()", and ASP.NET Validation i.e Reguired field Validation (ValidationGroup). Hence the Required field validators were not firing.

RequiredFieldValidator with ValidationSummary not working with enter key inside empty textbox

Consider the following ASPX:
<asp:ValidationSummary ID="vSummary" runat="server" CssClass="error-message" HeaderText="<p>Please correct the following errors with your profile.</p>" ShowMessageBox="false" DisplayMode="BulletList" ShowSummary="true" />
<asp:TextBox ID="txtTest" runat="server" ClientIDMode="Static"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfv" runat="server" Display="None" ErrorMessage="Enter a value in the textbox." ControlToValidate="txtTest"></asp:RequiredFieldValidator>
<asp:Button ID="btn1" runat="server" Text="Button 1" OnClick="btn1Click" ClientIDMode="Static" />
With text entered into the textbox, everything behaves as expected.
Clicking the button submits the form / pressing 'Enter' while inside the textbox submits the form.
However, when the textbox is empty, pressing 'enter' does nothing. Clicking the button will display the validation summary, as expected, but pressing 'enter' does not.
How can I make the validation summary display after the 'Enter' key is pressed inside an empty textbox?
For some reason when you hit enter error does not being displayed by ValidationSummary control. However, if you change in RequiredFieldValidator Display to "Dynamic" you will see error message.
Update: to overcome this problem try to follow instructions from this article.
For lazy ones:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// Add new attribute to form1 event to fire when enter key submit button click event
form1.Attributes.Add("onkeydown", "javascript: return WebForm_FireDefaultButton (event, '" + ButtonName.ClientID + "')");
// Allow you to use enter key for sumbit data
ClientScript.RegisterHiddenField("__EVENTTARGET", "ButtonName");
}
}
And finally:
// Add this code to div section on the form1 ASPX page.
<div id="inputArea" onkeypress="javascript:return WebForm_FireDefaultButton(event,'ButtonName')">
That behaviour is because your textbox is being validated but the validation message is not showing because you turned it off with Display = "none". It's doing the validation on client side and therefore, postback did not occur because of empty text.
If you remove the Validation control (which is not what you want) from the page, your text box will start posting back. I guess you don't want the message to show for each control, just in the validation summary, otherwise, that's the easiest way

Field validation of a single button only

I have the following validator on a textbox inside a modal dialog box.
<asp:RequiredFieldValidator runat = "server"
ErrorMessage = "Role name can not be empty."
ControlToValidate = "tbxRoleName" />
It works like it should, except that the validation triggers on every other buttons OnClick handler on the aspx-page too. Since the dialog is invisible it looks like buttons just dont work on the page. My workaround is to add CausesValidation = "false" on all buttons on the page. But it is a very bad solution and I think there should be a smarter way.
Assign ValidationGroup to each validator and also to the button that should trigger validation (but not the the other button). Something like:
<asp:RequiredFieldValidator ValidationGroup='valGroup1' ... />
<asp:Button ValidationGroup='valGroup1' Text='I trigger validation' ... />
How about setting a ValidationGroup?
http://msdn.microsoft.com/en-us/library/ms227424.aspx
Also you can use 'causesvalidation' to the button. If it is false Button will not response to Validation in aspx page.
Example:
<asp:Button runat="server" Text="Cancel" CausesValidation="false" />
The Button has a property CausesValidation that can disable the validation for that button.
More info here: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.button.causesvalidation.aspx

Resources