ASP.NET Prevent Form Validation with HTML 5 Submit Button - asp.net

I'm trying to use the HTML 5 button element to submit an ASP.NET form. I also want it to not trigger validation when clicked. This will submit the form, but will still cause validation to trigger:
<button runat="server"
CausesValidation="false"
type="submit"
name="myButton"
id="myButton">Press Here</button>
I'm specifically trying to not use HTML input or ASP:Button elements. They both will work, but don't allow HTML (images etc..) within the button text.
An example validation element on my page:
<asp:RequiredFieldValidator
ValidationGroup="myValGroup"
ControlToValidate="phone"
ID="phoneRequiredVal"
runat="server"
ErrorMessage="Phone is required."
Display="Dynamic"
CssClass="defaultErrorText"></asp:RequiredFieldValidator>
Any ideas?

Enter the LinkButton control. Looks like this is what I needed to submit the form, have HTML within the tags, and be able to halt validation:
<asp:LinkButton
runat="server"
CausesValidation="false"
CssClass="button fullWidth">Press Here</asp:LinkButton>
Found here:
How do I make a form submit with a LinkButton?

Although you use an HTML tag (<button>) as a server-side control (<button runat="server" ...>), the ASP.NET server does not expect this component as a postback or callback sender. As a result, the Event Validation error occurs on the server side during form submit.
To resolve this issue, register the button as a postback sender using ClientScriptManager.RegisterForEventValidation method:
public partial class _Default : System.Web.UI.Page
{
protected override void Render(HtmlTextWriter writer)
{
Page.ClientScript.RegisterForEventValidation("myButton");
base.Render(writer);
}
}

Related

Form data is saving and validation message is also displaying

We are using the callbackpanel for the validation of the Devexpress controls but what actually happening is :
If we click submit button without entering any thing in textboxes in the form. It is showing the validation messages but it is also saving the blank data to the database.
I want to know if validation message is showing then why event in backend is calling for saving data ?
Basically in DevExpress ASPxCallbackPanel, a Button Click does not trigger a Callback, it triggers a Postback that is the difference between an UpdatePanel and a CallbackPanel.
So you have to call the ASPxCallbackPanelClient.PerformCallback('PARAM'); instead.
You did not mention how you trigger the callback, you did not show how your ASPxButton code looks or how your ASPxCallbackPanel looks or how your Validator looks, so considering that please see code below that works very well in you scenario
All the controls as DX, including validators and buttons
<dx:ASPxCallbackPanel runat="server" ID="cbpDIActions" ClientInstanceName="cbpDIActions" OnCallback="cbpDIActions_Callback">
<panelcollection>
<dx:PanelContent>
<dx:ASPxSpinEdit ID="txtBuilFixtNoBathrooms" runat="server" ValidationSettings-RequiredField-IsRequired="true" ValidationSettings-ValidationGroup="SubmitValidation">
</dx:ASPxSpinEdit>
<dx:ASPxButton ID="btn" runat="server" AutoPostBack="false" Text="Process" UseSubmitBehavior="False"
ValidationSettings-ValidationGroup="SubmitValidation" CausesValidation="true"
>
<ClientSideEvents Click="function(s,e){
ASPxClientEdit.ValidateGroup('SubmitValidation');
if (ASPxClientEdit.AreEditorsValid()) {
if(!cbpDIActions.InCallback()) {
cbpDIActions.PerformCallback('PARAM');}
}
}" />
</dx:ASPxButton>
</dx:PanelContent>
</PanelCollection>
</dx:ASPxCallbackPanel>
And in the backend you put all your code in the callback event
protected void cbpDIActions_Callback(object sender, DevExpress.Web.CallbackEventArgsBase e)
{
if (e.Parameter != null && e.Parameter.ToString() == "PARAM")
{
//PROCESS YOUR CODE
}
}

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

Difference between button and asp:button onclick

I am new to developing in asp.net for making web sites.
What is the difference between an asp:Button and an input button?
Code 1
aspx code
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
Codebehind
protected void Button1_Click(object sender, EventArgs e)
{
//Do somthing
}
Code 2
aspx code
<input id="Submit1" type="submit" value="submit" onclick="return Submit1_onclick()" />
<script language="javascript" type="text/javascript">
// <![CDATA[
function Submit1_onclick() {
//Do somthing
}
// ]]>
</script>
The first code it is a server side code. When you add a tag asp:button in your webform, the asp.net will render an input type="button" for you and when you click this button, it will submit a post to the same page (this is called postback) and will processing the life cycle and asp.net event associated with this button. The same is valid for every server control such as TextBoxes (render input type='text'), Panels (renders divs), Checkboxes (render input type='checkbox'), Labels (render spans) etc...
In the second code, you have the code that first one will render (an input type = 'button'), but associated with an event in the client-side javascript.
You can also associate a client-side event in a tag asp:button, take a look at the OnClientClick property.
asp:Button is an asp.net server control which fire an event on the server side.
<input id="Submit1" type="submit"
is a client side button of type submit,
but it can act as a server side button as well by adding
runat="server" and onserverclick="eventname"
The first is a server side control and the event handler is executed on the server in C#. Clicking the button will cause a postback and all information in the form will be posted to the server for processing, including a call to the click event handler.
The second is fully client side and the event handler is executed in the browser in JavaScript.
to my understanding you have to keep in mind that there is a cliend side code that will execute, for example javascript in your browser, and asp/c# code that will execute on the server.
So having this control:
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
Button1_Click will execute on the server, in microsoft world it is IIS, on the other hand
you have just a pure html control, where you hook up a javascript function for the click event
<input id="Submit1" type="submit" value="submit" onclick="return Submit1_onclick()" />
So the server side has nothing to do with this part, this code will execute on your machine, in your browser.
A mí me funcionó así:
1.- En el botón:
<input type="submit" id="btnAccept" value="Log In" runat="server" onserverclick="btnAccept_Click">
2.- En el codebehind:
Protected Sub btnAccept_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)

UserControl conditional validation approach?

I have a custom UserControl which contains several TextBoxes with Validators. One TextBox with corresponding Validator is optional based on a CheckBox. Pseudo:
My Control.ascx:
<asp:TextBox id="txtAddress" />
<asp:Validator id="valAddress" />
<asp:CheckBox id="condition" />
<asp:TextBox id="txtConditional" />
<asp:Validator id="valConditional" ValidationGroup="ConditionalGroup" />
My Control.ascx.cs
public void Validate() {
if(condition.Checked) {
Page.Validate("ConditionalGroup");
}
}
I also have a page which basically looks like this:
Page.aspx
<my:Control id="myControl" />
<asp:Button onClick="doPost" />
Page.aspx.cs
protected void doPost(object sender, EventArgs e) {
myControl.Validate(); //This feels wrong
if(Page.IsValid) {
//go
}
}
This all works, however I would like to take the myControl.Validate() line out of the Page.aspx.cs and put it in the My Control.ascx.cs. Putting it in the Page_Load of the control is not an option because the conditional checkbox value is always false. There is no event available after Page_Load and before the doPost click handler is fired...
It feels wrong to call the custom Validate function on the Page where I think it should belong somewhere in the UserControl. Is it true that this is architecturally wrong? Is there another solution for this maybe by using an event handler?
You could try by enabling the validator only if the user checks on the check box. And disable the validator if the unchecks it. This has to be done in the user control. It can be done in the client side or in the server side. In this way, the page would validate all the validators that are enabled for the page.

Page Validation, Submit Button is not part of the usercontrol

I have some fields to be validated on the server (CustomValidator) which is in a separate user control and my Submit button is in the page not in the user control.
What I have done is, I placed all my Validation Methods in the code behind of my usercontrol (ascx.cs) and the page validation is in the code behind of the page (aspx.cs). I put them in the same ValidationGroupName (fields and Submit button). usercontrol (ascx) is a child of my page (aspx). I have already placed CauseValidation="true" to my Button and UseSubmitBehavior="true". The problem is it does not validate. What could be the problem in this?
Note: I cannot put the the Button to be part of the usercontrol.
Edit:
in my aspx page, click event of the button has this.Page.Validate(ValidationGroupName) and all of my validators are on the fields on a separate control (ascx) which is a child of the aspx page.
protected void Button1_Command(object sender, CommandEventArgs e)
{
if(e.CommandName.Equals("Validate", StringComparison.Ordinal))
{
this.Page.Validate("MyValidationGroup");
if(this.Page.IsValid)
{
// I'll change my View here.
}
}
}
My Button looks like
<asp:Button ID="Button1" runat="server" UseSubmitBehavior="true" CommandName="Validate"
Text="Submit" OnCommand="Button1_Command" CausesValidation="true" ValidationGroup="MyValidationGroup" />
The above snippet is located in my aspx page.
I've tried to put the same button on the ascx page, it works fine. My thought is since the ascx page is under the aspx page. When the button event on aspx page is fired (Button1), the rest of the event in ascx page is not fired. I've tried to put breakpoints on the button event and validator events, if the button of the page (aspx) is the one I click, it will not stop on my validator events, if the button on the control (ascx) I click it will stop to the validator events. What could be the remedy for this?
Have you tried calling ucName.Page.Validate(); in the button click event?
(where ucName is whatever you called the user control in the markup)
Edit: OK this simple code below works fine for me, the only way I broke the validation was setting my user control to visible = false; Can you post more of your code?
Parent page markup:
<uc:ucTest id="ucName" runat="server">
<asp:Button ID="btnTest" runat="server" Text="Test validation" onclick="btnTest_Click" />
code behind:
protected void btnTest_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
Response.Write("Hi!");
}
}
user control markup:
<asp:TextBox ID="txtDummy" runat="server"></asp:TextBox>
<asp:CustomValidator ID="CustomValidator1" runat="server"
ErrorMessage="*"
ControlToValidate="txtDummy"
onservervalidate="CustomValidator1_ServerValidate">
</asp:CustomValidator>
code behind:
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
if (txtDummy.Text.Length > 0)
{
args.IsValid = false;
}
}

Resources