I have four textboxes and I need to check for null values. If any of the textbox value has null values then on button click I need to show a alert like 'Please enter values'.
This code will disable if textbox value is empty.
ASPX:
<tr style="height: 40px;">
<td>
<asp:textbox id="txt1" runat="server">
</asp:textbox>
</td>
<td>
<asp:textbox id="txt2" runat="server">
</asp:textbox>
</td>
<td>
<asp:textbox id="txt3" runat="server">
</asp:textbox>
</td>
</tr>
<tr>
<td>
<asp:button id="Button1" runat="server" text="Add" cssclass="button" width="50px"
onclick="Button1_Click" /></td>
</tr>
CS:
protected void Button1_Click(object sender, EventArgs e)
{
if (String.IsNullOrWhiteSpace(txt1.Text) || String.IsNullOrWhiteSpace(txt2.Text) || String.IsNullOrWhiteSpace(txt3.Text))
{
string message = "Textbox can be empty, please enter a value";
string script = String.Format("alert('{0}');", message);
this.Page.ClientScript.RegisterStartupScript(this.Page.GetType(), "msgbox", script, true);
}
if (txt1.Text != "" && txt2.Text != "" && txt3.Text != "" && ddlcategory.Text != "--Select--")
{
DataSet ds = new DataSet();
using (SqlConnection connection = new SqlConnection(str))
{
SqlCommand command = new SqlCommand();
command.Connection = connection;
string strquery = "select * from product where code='Metal' and Id='" + txt1.Text + "'";
SqlCommand cmd = new SqlCommand(strquery, connection);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
}
if (ds.Tables[0].Rows.Count > 0)
{
ClientScript.RegisterStartupScript(this.GetType(),"Key", "<script type='text/javascript'>window.onload = function(){alert('Product Already Exists.');return false;}</script>");
}
else
{
SqlConnection conn = new SqlConnection(str);
conn.Open();
SqlCommand cmd = new SqlCommand("Products", conn);
cmd.Parameters.Add("#id", SqlDbType.VarChar, 30).Value = txt1.Text;
cmd.Parameters.Add("#name", SqlDbType.VarChar, 50).Value = txt2.Text;
cmd.Parameters.Add("#email", SqlDbType.VarChar, 30).Value = txt3.Text;
cmd.Parameters.Add("#category", SqlDbType.VarChar, 20).Value = ddlcategory.Text;
cmd.Parameters.Add("#id", SqlDbType.Int).Value = 1;
cmd.CommandType = CommandType.StoredProcedure;
cmd.ExecuteNonQuery();
conn.Close();
conn.Dispose();
ClientScript.RegisterStartupScript(this.GetType(), "Key", "<script type='text/javascript'>window.onload = function(){alert('Product Created Successfully.');return false;}</script>");
}
}
}
Anyone suggest me on this.
try below
if (String.IsNullOrWhiteSpace(txt1.Text) || String.IsNullOrWhiteSpace(txt2.Text) || String.IsNullOrWhiteSpace(txt3.Text) || String.IsNullOrWhiteSpace(txt4.Text))
{
string message = "Please enter values";
string script = String.Format("alert('{0}');", message);
this.Page.ClientScript.RegisterStartupScript(this.Page.GetType(), "msgbox", script, true);
return;
}
You can do this in client side with JavaScript code
function verifyValues()
{
var txtBox1,txtBox2,txtBox3,txtBox4;
txtBox1=document.getElementByID("<%= myTextBox1.ClientID %>"):
txtBox2=document.getElementByID("<%= myTextBox2.ClientID %>"):
txtBox3=document.getElementByID("<%= myTextBox3.ClientID %>"):
txtBox4=document.getElementByID("<%= myTextBox4.ClientID %>"):
if(txtBox1.value=="" || txtBox2.value==""||txtBox3.value==""
|| txtBox4.value=="")
{
alert("Please enter any one of the value");
return false;
}
return true;
}
Then your server side Markup should call javascript function with return statement
<asp:Button ID="btnSubmit" runat="server" OnClientClick="return verifyValues();"
Text="Click" />
If you want double check both client and server side, please include #Damith answer in server side validation
I would use string.IsNullOrEmpty() instead and do the below.
if (string.IsNullOrEmpty(txt1.Text)) {
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(),
"err_msg",
"alert('Please enter values!)');",
true);
}
Try This one
if (txt1.Text == "" || txt2.Text == "" || txt3.Text == "" || txt4.Text == "")
{
ScriptManager.RegisterStartupScript(this.Page, typeof(Page), "scrip1", "alert('Enter All fields');", true);
Button1.Enabled = false;
}
else
{
Button1.Enabled = true;
}
Apply Required Field Validation on all the Textboxes and provide Group Name for all textboxes and for button on click of which validation should work, group name should be same for all the textboxes and for button.
This is exactly what you are looking for: (Server side validation for multiple control)
http://www.codeproject.com/Tips/722385/Single-Server-Side-Validator-for-Multiple-Controls
try this instead of your code, and should be add return false after alert message showed
if (string.IsNullOrEmpty(txt1.Text) ||string.IsNullOrEmpty( txt2.Text) || string.IsNullOrEmpty(txt3.Text) || string.IsNullOrEmpty(txt4.Text))
{
string script = "<script type=\"text/javascript\">alert('Please enter values');</script>";
ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", script);
Button1.Enabled = false;
return false;
}
else
{
Button1.Enabled = true;
}
}
or
if (string.IsNullOrEmpty(txt1.Text) ||string.IsNullOrEmpty( txt2.Text) || string.IsNullOrEmpty(txt3.Text) || string.IsNullOrEmpty(txt4.Text))
{
string script = "alert('Please enter values');";
ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", script, true);
Button1.Enabled = false;
return false;
}
else
{
Button1.Enabled = true;
}
}
you have to do this validation at client side which gives u improved performance
as follow
function verifyValues()
{
var txtBox1,txtBox2,txtBox3,txtBox4;
txtBox1=document.getElementByID("txt2"):
txtBox2=document.getElementByID("txt2"):
txtBox3=document.getElementByID("txt2"):
txtBox4=document.getElementByID("txt2"):
if(txtBox1.value=="" || txtBox2.value==""||txtBox3.value==""
|| txtBox4.value=="")
{
alert("Please enter any one of the value");
return false;
}
return true;
}
Related
I have ASP.NET WEB FORMS apps
<asp:Button ID="DeleteDealsButton" runat="server" Text="Delete" />
function btnDeleteClick() {
var result = confirm("Want to delete all Deals?");
if (result) {
return true;
} else {
return false;
}
}
$("#MainContent_DeleteDealsButton").on("click", function() {
if (btnDeleteClick()) {})
On this button I have sample javascript alert to ask OK or Cancel.I want if choise OK to fire CODE BEHIND method call DeleteDealsButton_Click, if it Cancel to do nothing.
Just change button defination to,
<asp:Button ID="DeleteDealsButton" runat="server" Text="Delete" OnClientClick="return confirm('Want to delete all Deals?')" />
No need for any javascript function.
try like this:
function btnDeleteClick() {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
confirm_value.value = "No";
var result = confirm("Want to delete all Deals?");
if (result) {
confirm_value.value = "Yes";
__doPostBack('DeleteDealsButton', '')
return true;
} else {
confirm_value.value = "No";
return false;
}
}
In your .Aspx file Change your button code to like this:
<asp:Button ID="DeleteDealsButton" OnClientClick=" return btnDeleteClick()" runat="server" Text="Delete" OnClick="DeleteDealsButton_Click" />
In your .Aspx.cs file
protected void DeleteDealsButton_Click(object sender, EventArgs e)
{
string confirmValue = Request.Form["confirm_value"];
if (!String.IsNullOrWhiteSpace(confirmValue) && confirmValue.Equals("Yes"))
{
}
}
i want to show a javascript confirm box on the client side under OnChange event "chkIsActive_CheckedChanged". i am using registerStartupscript int the code behind for this purpose. this confirm message is displaying fine but it is displaying after end of the event "chkIsActive_CheckedChanged". i want to display the confirm message while executing in the function. Please help me out.
My HTML
<asp:CheckBox ID="lbl_IsActive" runat="server" OnCheckedChanged="chkIsActive_CheckedChanged" AutoPostBack="true" Checked='<%# Eval("IsActive") %>' ></asp:CheckBox>
My javascript
<script type = "text/javascript">
function Confirm() {
var confirm_value = document.getElementById("<%=IsChecked.ClientID%>");
if (confirm("Do you want to save data?")) {
confirm_value.value = "1";
} else {
confirm_value.value = "0";
}
}
</script>
my C# code behind
protected void chkIsActive_CheckedChanged(object sender, EventArgs e)
{
ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "MyFun1", "Confirm();", true);
string confirmValue = IsChecked.Value;
if (confirmValue == "1")
{
string CarEstimateID = "";
Entities.CarEstimateFirms ObjEst = new Entities.CarEstimateFirms();
CheckBox chk = (CheckBox)sender;
GridViewRow gr = (GridViewRow)chk.Parent.Parent;
CarEstimateID = (GridView1.Rows[gr.RowIndex].FindControl("lbl_CarEstimateFirmID") as Label).Text; // GridView1.DataKeys[gr.RowIndex].Value.ToString();
ObjEst.CarEstimateFirmID = Convert.ToInt32(CarEstimateID);
ObjEst.IsActive = chk.Checked;
BLL.Common.UpdateCarEstimateFirms(ObjEst);
BindGridView();
}
}
Add onchange javascript event in your checkbox:
<asp:CheckBox ID="lbl_IsActive" runat="server" OnCheckedChanged="chkIsActive_CheckedChanged" AutoPostBack="true"
Checked='<%# Eval("IsActive") %>' onchange="javascript:return Confirm();" ></asp:CheckBox>
Your javascript confirm method should be like below:
<script type = "text/javascript">
function Confirm() {
if (confirm("Do you want to save data?")) {
return true;
} else {
return false;
}
}
</script>
And remove below line from chkIsActive_CheckedChanged event from code behind:
ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "MyFun1", "Confirm();", true);
When I click my Button to perform the validation, the validation happens correctly on the server side, but at the same time my client side validation always says the page is valid even when the page is not valid on the server side.
HTML
<telerik:RadComboBox ID="PURSubAccounts" runat="server" Width="150" EmptyMessage=" ---" Font-Bold="true"></telerik:RadComboBox>
<asp:RequiredFieldValidator id="PurSubValidation" runat="server" ErrorMessage="!!!" Display="Dynamic" Font-Bold="true" Font-Italic="true" ForeColor="Red" InitialValue="" ControlToValidate="PURSubAccounts" EnableClientScript="true"></asp:RequiredFieldValidator>
<asp:Button ID="CreateButton" runat="server" CausesValidation="true" OnClick="CreateButton_Click" OnClientClick="ValidateME();" />
JavaScript
function ValidateME() {
if (Page_IsValid) {
alert("Valid");
} else {
alert("NOT Valid");
}
}
VB Code
Protected Sub CreateButton_Click(sender As Object, e As EventArgs)
If Page.IsValid Then
msgbox("Valid")
Else
msgbox("NOT Valid")
End If
End Sub
So when I click the button, The vb messagebox says "NOT Valid" and the clientside Alert says "Valid" whilst my error messages on the requiredfieldvalidators are correctly displayed.
I have tried using the Page_ClientValidate() but that also returns true whilst serverside returns false.
How do I go about getting the validations to agree?
Use Custom validor rather than Required field validator:
<asp:CustomValidator ID="CustomValidator1" runat="server" ClientValidationFunction="validateCombo" ErrorMessage="You must select an item with even value" OnServerValidate="CustomValidator1_ServerValidate"></asp:CustomValidator>
For your client side validation :
function validateCombo(source, args)
{
args.IsValid = false;
var combo = $find("<%= RadComboBox1.ClientID %>");
var text = combo.get_text();
if (text.length < 1)
{
args.IsValid = false;
}
else
{
var node = combo.findItemByText(text);
if (node)
{
var value = node.get_value();
if (value.length > 0 && value % 2 == 0)
{
args.IsValid = true;
}
}
else
{
args.IsValid = false;
}
}
}
Please try this for server side validation and let me know if it works for you.
string selectedValue = RadComboBox1.SelectedValue;
if (selectedValue != null && selectedValue.Length > 0)
{
try
{
int value = Convert.ToInt32(selectedValue);
if (value % 2 == 0)
args.IsValid = true;
else
args.IsValid = false;
}
catch (Exception ex)
{
args.IsValid = false;
}
}
else
args.IsValid = false;
In the below code i have a javascript function and a textbox.The validations are working perfectly.My aim if the validation fails it should clear the textbox value and cursor should be in the same textbox it should not move to other controls.
JS:
function ValidateRegExp(txtInput, REGEXP) {
var mySplitResult = new Array();
mySplitResult = REGEXP.split("~~");
var iReturn = 0;
for (i = 0; i < mySplitResult.length - 1; i++) {
var re = new RegExp(mySplitResult[i]);
if (!txtInput.match(re)) {
iReturn = iReturn + 1;
}
}
if (iReturn > 0) {
alert("Failed...");
} else {
alert("Success...");
}
}
codebehind:
txtField.Attributes.Add("onblur", "javascript:ValidateRegExp(document.getElementById('" + txtField.ClientID + "').value, '" + hidRegExp.Value + "');");
I don't know why it is not working for me this works I have just created a simple example by taking 2 textboxes
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtField" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</div>
</form>
and this is my script
<script type="text/javascript">
function validate() {
var txt = document.getElementById("txtField");
if (txt.value === "" || txt.value.length <= 1) {
txt.value = ''; // to clear the textbox value
txt.focus(); // focus on the textbox
}
}
</script>
This is in aspx.cs file
protected void Page_Load(object sender, EventArgs e)
{
txtField.Attributes.Add("onblur", "javascript:validate()");
}
On Leave event or the blur even of every control you can call the validate() function. There is a property that focuses on invalid input. so it will stuck to the textbox till the valid data is put.
http://jqueryvalidation.org/validate/
I have a quick question. I have a dropDownList that I'm trying to get populated with id's from a stored procedure. However it doesn't seem to work. this is my dropDownlist:
<div id="newExpenseTypeDialog" style="display:none;">
<label>Select new CaseFile:</label>
<asp:DropDownList runat="server" ID="ddlCaseFiles" DataSourceID="dsMyCaseFiles" DataTextField="Display" DataValueField="FileID" OnPreRender="ddl_PreRender" Width="524px" />
</div>
And this is my DataSource:
<asp:SqlDataSource ID="dsMyCaseFiles" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" ProviderName="System.Data.SqlClient" SelectCommand="p_CaseFiles_ListActiveCaseFilesAssignedTo" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:SessionParameter Name="InvestigatorID" SessionField="InvestigatorID" />
<asp:SessionParameter Name="AssignedTo" SessionField="InvestigatorID" />
</SelectParameters>
</asp:SqlDataSource>
My Stored procedure needs two parameter. InvestigatorID and AssignedTo. It will then find return all the FileID's that match.
Now this is my .aspx.cs side code :
(Page_load)
if (Request.QueryString["ExpenseID"] != null)
{
if (!IsPostBack)
{
ddlCaseFiles.DataSourceID = "dsCaseFiles";
ddlCaseFiles.DataTextField = "Display";
ddlCaseFiles.DataValueField = "FileID";
}
}
and my Pre_Render:
protected void ddl_PreRender(object sender, EventArgs e)
{
DropDownList ddl = (DropDownList)sender;
try
{
if (ddl.Items[0].Value != "-1")
ddl.Items.Insert(0, new ListItem("--Select--", "-1"));
}
catch
{
ddl.Items.Insert(0, new ListItem("--Select--", "-1"));
}
}
The list has the pre_render working and what not, just no data from my stored procedure.
i think you just forget to call DataBind method
ddlCaseFiles.DataBind();
in if(!ispostback) block after that three line
You haven't Binded your dropdown list yet
if (Request.QueryString["ExpenseID"] != null)
{
if (!IsPostBack)
{
ddlCaseFiles.DataSourceID = "dsCaseFiles";
ddlCaseFiles.DataTextField = "Display";
ddlCaseFiles.DataValueField = "FileID";
ddlCaseFiles.DataBind(); //You need to Bind it here
}
}
Hope this will help you