disabled a submitt button c# asp.net - c#

if (string.IsNullOrWhiteSpace(TextBox1.Text))
{
Button1.Enabled = false;
}
else
{
Button1.Enabled = true;
}
Hi,
I have a form with 3 TextBoxes and I want the submit button doesn't send any data if any of them are empty,
I already use RequiredFieldValidator but how I can prevent user from submit until they filled all boxes
I tried the code above ^

you need some client side javascript..
at its simplest...
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" OnClientClick="return checkRequireds()" runat="server" Text="Button" />
<script>
function checkRequireds() {
var textBox = document.getElementById('<%=TextBox1.ClientID%>');
return !(textBox.value == 'undefined' || textBox.value == '')
}
</script>
PS: If you use the required field validator, you have already blocked the page from posting

Related

How to prevent the trigger of another button

I have the following in my ASP.net page:
<input type="text" placeholder="Search..." size="30" id="pageLink" />
<br />
<span id="imgGo" class="imgGo floatRight"></span>
JQuery:
$('.imgGo').click(function () {
var strString = $("#pageLink").val()
var strSearch = "http://www.google.com/search=";
var url = strSearch + strString;
window.open(url, '_blank');
return false;
});
$("#pageLink").keyup(function (event) {
if (event.keyCode == 13 || event.which == 13) {
$(".imgGo").click();
}
});
When I enter something in the textbox and click the imgGo span it works fine but if instead I hit enter, my search button which is in another panels gets triggered.
How can I either modify my JQuery code to ensure that doesn't happen or add code-behind to ensure imgGo is triggered only if enter button is pressed while the pageLink textbox has the focus?
I tried the following but didn't work because imgGo is not a button:
<asp:Panel ID="pnlMedSearch" runat="server" DefaultButton="GoImg">
<!--<input type="text" placeholder="Search..." size="30" id="p2" />-->
<asp:TextBox Width="30" ID="pageLink" runat="server" />
<br />
<!--<span id="imgGo" class="imgGo floatRight"></span>-->
<asp:Label ID="imgGo" CssClass="imgGo floatRight" runat="server" />
</asp:Panel>
I get the following error:
The DefaultButton of 'pnlMedSearch' must be the ID of a control of type IButtonControl.
I would like to use the textbox which is not a ASP.net control because the placeholder attribute is important in my case.
I kept the same HTML content and modified my Jquery to the following:
$("#medlineSearch").keypress(function (event) {
if (event.which == 13) {
$("#imgGo").click();
return false;
}
});
Adding the return false; ensure it didn't invoke anything else on the page.
Alternate version for the same.
Register as an event on any tags:
onkeydown="pressButtonOnEnter('IdOfMyButton', event);"
Into your .js file:
function pressButtonOnEnter(buttonId, event) {
var key = (evt.which) ? evt.which : evt.keyCode;
if (key == 13) {
$("#" + buttonId).click();
}
}
It works in asp.net as well.You can simply add it to an asp:textbox for instance.

Show Message Box if TextBox is Blank or Empty using C#

I am trying to check first if users don not enter either User ID or Password, if either text box is blank or empty then I want to show message box, if they enter both user id and password then I want to execute some other codes. The problem I am having with the code is that the message does not show at all but the good thing is that it does not execute the other code. So I would like to see the message box to show up if both text boxes are empty. I am not sure why the message box is not showing up even though I have used this same code in other functions and it worked. thanks
here is my button code for the ASPX
<asp:Panel ID="Panel1" runat="server" BorderStyle="Groove" Height="109px" Visible="false"
Width="870px" BackColor="#FFFFE1">
<asp:Label ID="Label2" runat="server" Text="DIGITAL SIGNATURE" Font-Bold="True"
ForeColor="#FF3300"></asp:Label>
<br />
<br />
<asp:Label ID="lblUID" runat="server" Text="User ID:"></asp:Label>
<asp:TextBox ID="txtUID" runat="server" Height="22px" Width="145px"></asp:TextBox>
<asp:Label ID="lblPass" runat="server" Text="Password:"></asp:Label>
<asp:TextBox ID="txtPass" runat="server" Height="23px" TextMode="Password" style="margin-top: 0px"></asp:TextBox>
<br />
<br />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" Width="183px"
onclick="btnSubmit_Click"
OnClientClick="return confirm('Are you sure you want to submit?');"
Font-Bold="False" Font-Size="Medium" Height="30px"
style="margin-right: 1px" />
<br />
</asp:Panel>
code behind:
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (txtUID.Text.Length == 0 || txtPass.Text.Length == 0)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Please type your User ID and Password correctly and click Submit button again. Thanks", true);
}
else
{
//execute some code here
}
}
In your code in btnSubmit_Click method, when you call RegisterClientScriptBlock you missed '); symbols at then end of your alert. So, your javascript is incorrect, and browser displays an error in developers tools. It should be like this:
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (txtUID.Text.Length == 0 || txtPass.Text.Length == 0)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(),
"alertMessage",
"alert('Please type your User ID and Password correctly and click Submit button again. Thanks');", true);
}
else
{
//execute some code here
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (txtUID.Text.Length == 0 || txtPass.Text.Length == 0)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "alertMessage", "alert('Please type your User ID and Password correctly and click Submit button again. Thanks');", true);
}
else
{
//execute some code here
}
}
One approach would be to do this client-side. You could change your OnClientClick to:
return login();
and then build the login function:
function login() {
if ($('#txtUID').val() === '' ||
$('#txtPass').val() === '') {
alert('Please type your User ID and Password correctly and click Submit button again. Thanks');
return false;
}
return confirm('Are you sure you want to submit?');
}
and so now you can get rid of the server-side code.
I have created common .js file which contains all client side validation as
function checkMandatory(ele)
{
var text;
text = ele.value;
if(text.length == 0)
{
alert("Please enter value ...");
ele.focus();
return;
}
}
Call function in Page_Load event as
txtName.Attributes.Add("onFocusout", "checkMandatory(this);");
Note: Dont forget to include .js file to your page inside HTML tags.

Validate two controls (CustomValidator)

Before submitting the form I need to test if the sum ( txtA + txtB) is greater than 100. Is it possible to do this with a CustomValidator, because I don't know if I can choose the 2 textbox in controltovalidate
<asp:TextBox ID="txtA" runat="server"></asp:TextBox>
<asp:TextBox ID="txtB" runat="server"></asp:TextBox>
<asp:CustomValidator ID="CustomValidator2"
runat="server"
ErrorMessage="CustomValidator" />
<asp:Button ID="Button1" runat="server" Text="Button" />
Thanks.
you can do as :
<asp:TextBox ID="txtA" runat="server" />
<asp:TextBox ID="txtB" runat="server" />
<asp:CustomValidator ID="CV1"runat="server"
OnServerValidate="ServerValidation"
ErrorMessage="Sum is less than 100" />
codebehind :
protected void ServerValidation(object source, ServerValidateEventArgs args)
{
args.IsValid = int.Parse(txtA.Text)+ int.Parse(txtB.Text) >100;
}
When you drop a custom validation in your page, you can link the validator to a control, but if you want to perform multiple validations over more than one control, you need to include the following attribute
OnServerValidate="MyMethodOnServerSide"
and define that method on the server side
protected void MyMethodOnServerSide(object source, ServerValidateEventArgs args)
{
if (string.IsNullOrEmpty(mytxt1.Text) &&
string.IsNullOrEmpty(mytxt2.Text))
{
args.IsValid = false;
return;
}
args.IsValid = true;
}
just asign the args.IsValid property to the value you need. On the other hand the validation is done before you load the page, so if you clicked a button that performs an action like reading values from the DB in case everything is correct, on that action you need to include the following check.
protected void cmdSearch_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
LoadDataFromDB();
}
}
When args.IsValid is false then Page.IsValid is false too. Hope this helps
You need to add another control, <asp:HiddenField> and then leverage jQuery to set the value of that control. It might look something like this:
MARKUP
<asp:HiddenField ID="SumOfValues" />
<asp:CustomValidator ID="CustomValidator2"
runat="server"
ErrorMessage="CustomValidator"
ControlToValidate="SumOfValues" />
JQUERY
$(document).ready(function() {
$('#txtA').change(sumValues);
$('#txtB').change(sumValues);
});
function sumValues() {
var val1 = $('txtA').value();
if (val1 === undefined) { val1 = 0; }
var val2 = $('txtB').value();
if (val2 === undefined) { val2 = 0; }
$('#SumOfValues').value(val1 + val2);
}
and that should allow you validate that hidden control. However, one thing you'll need to make sure to do on all three controls is leverage ClientIDMode and set it to Static so that the names are exactly what you specify in the markup when they get to the page.

asp.net c# validation

I am trying to create a simple form that uses radio buttons. I set the radio button to AutoPostBack = True, this way if the radio button is true/false, a subpanel is Shown or Hidden. The radio buttons are required fields. I also have a hidden textbox that the value of the selected radio button is inserted and this textbox is what I validate against (empty or not).
Problem 1:
This works until you go to submit and the validation fails. The validation messages show, then when you click on one of the radio buttons with AutoPostBack = True, all the validation disappear. I can resolve this by adding Page.Validate() to the method that runs when the radio button is clicked. But, I do not want the Page.Validate() to run unless the page was already showing validation errors (so it will not re-validate unless the form was already submitted and failed the validation).
As it stands, before the form is submitted and fails validation: when you click on any radio button question, all the other questions requiring validation show the validation error. I am only looking to overcome the AutoPostBack which is clearing all the validation messages that are shown when you had click submit.
Problem 2:
I would like to be able to change the color of the question if it does not pass validation. I added the javascript to override the default .net settings. I got this to work, but only when you click the submit button and not after a RadioButton AutoPostBack.
Currently, When you click submit all the required questions turn red and also display the required validation message. But if you click a radio button to start fixing the validation errors, on the AutoPostBack, the all the questions that were now red in color changes back to the orignal black and the required validation message is still shown. How can I call the Javascript to run again along with the Page.Validation() in the code behind method?
Any help would be greatly appricated! Thanks
Below is an example of the code so far.
ASPX Code:
<asp:Table ID="Table1" runat="server" CellSpacing="0" CellPadding="0">
<asp:TableRow>
<asp:TableCell CssClass="question">
<label>4. Have you had an abnormal result from a prenatal test (e.g. amniocentesis, blood test, ultrasound)?</label>
</asp:TableCell>
<asp:TableCell CssClass="answer">
<ul class="selectGroup">
<li>
<asp:RadioButton ID="Q4_true" runat="server" Checked='<%# Bind("Q4_yes") %>' Text="Yes"
GroupName="4" OnCheckedChanged='RB_QuestionSubPane_YN' AutoPostBack="true" /></li>
<li>
<asp:RadioButton ID="Q4_false" runat="server" Checked='<%# Bind("Q4_no") %>' Text="No"
GroupName="4" OnCheckedChanged='RB_QuestionSubPane_YN' AutoPostBack="true" />
</li>
<asp:TextBox ID="Q4_validationBox" runat="server" CssClass="hiddenField" Enabled="false"
Text=''></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" EnableViewState="true" ControlToValidate="Q4_validationBox"
Display="Dynamic" runat="server" ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator>
</ul>
</asp:TableCell>
</asp:TableRow>
</asp:Table>
Code Behind
protected void RB_QuestionSubPane_YN(object sender, EventArgs e)
{
RadioButton radio_Selected = (RadioButton)sender;
string radio_QuestionID = Convert.ToString(radio_Selected.ID);
(((TextBox)FormView1.FindControl(strQuestionID + "_validationBox")).Text) = radio_Selected.ID.ToString();
Page.Validate();
}
JavaScript
ValidatorUpdateDisplay = function (val) {
var ctl = $('#' + val.controltovalidate);
var eCount = 0;
for (var i = 0; i < Page_Validators.length; i++) {
var v = Page_Validators[i];
if (v.controltovalidate == val.controltovalidate) {
if (!v.isvalid) {
eCount++;
ctl.addClass('validationError');
$('td.question:eq(' + i + ')').addClass('red');
}
};
}
if (eCount > 0) {
ctl.addClass('validationError');
} else {
ctl.removeClass('validationError');
$('td.question:eq(' + i + ')').removeClass('red');
}
if (typeof (val.display) == "string") {
if (val.display == "None") {
return;
}
if (val.display == "Dynamic") {
val.style.display = val.isvalid ? "none" : "inline";
return;
}
}
if ((navigator.userAgent.indexOf("Mac") > -1) &&
(navigator.userAgent.indexOf("MSIE") > -1)) {
val.style.display = "inline";
}
val.style.visibility = val.isvalid ? "hidden" : "visible";
}
It sounds like what you really need is custom validation. That way you can fully customize your validation to meet your needs.
Here is a simple example:
<script language="javascript" type="text/javascript" >
function CustomValidator1_ClientValidate(source,args)
{
//put your javascript logic here
}
//-->
</script>
<body>
<form id="form1" runat="server">
<div>
<asp:RadioButton ID="RadioButton1" runat="server" GroupName="direction" Text="left" />
<asp:RadioButton ID="RadioButton2" runat="server" GroupName="direction" Text="right" />
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
<asp:CustomValidator id="CustomValidator1" runat="server" Display="Dynamic" ErrorMessage="please choose" ClientValidationFunction="CustomValidator1_ClientValidate" OnServerValidate="CustomValidator1_ServerValidate"></asp:CustomValidator>
</div>
</form>
</body>
Server Side
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
args.IsValid = RadioButton1.Checked || RadioButton2.Checked;
}
protected void Button1_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
//validate is successful.
}
}

asp:button Return behaviour

I have a bunch of buttons on my page and beside a textbox I have a Search button.
Now when I hit the return key on the keyboard it actually activates the Add user button which is right above.
How to link the textbox with the search button?
You can set the default button for your form:
<form id="form1" runat="server" defaultbutton="btn1">
You can use asp:panel for setting default button.
<form runat="server">
<asp:Panel runat="server" DefaultButton="bt1">
<asp:TextBox runat="server" />
<asp:Button id="bt1" Text="Default" runat="server" />
</asp:Panel>
</form>
Following javascript method will do it for you:
function clickButton(e, buttonid){
var evt = e ? e : window.event;
var bt = document.getElementById(buttonid);
if (bt){
if (evt.keyCode == 13){
bt.click();
return false;
}
}
}
In code behind, attach this event with your textbox like:
TextBox1.Attributes.Add("onkeypress", "return clickButton(event,'" + Button1.ClientID + "')");

Categories

Resources