Using IF..ELSE in UPDATE Query
Using IF..ELSE in UPDATE:
SQL:
Select Query:
select propertyid,e.name as username,case p.bactive when 1 then 'tick.gif' else 'cross.gif' end as bActive from tbl_Property p inner join enquiry e on p.userid=e.enqiry_id"
Update Query:
update tbl_Property set bactive=(case bactive when '1' then '0' else '1' end) where propertyid=14DBManager
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections;
using System.IO;
using System.Collections.Specialized;
using System.Text;
using System.Data.Odbc;
using ESNAS;
using ESNLib;
public class DBManager
{
public static string connStr;
public static string USATIME = "05:00:00";
// total commands to execute
public static int intCommands = 0;
// the string array with queries
public static string[] QueryCollection = new string[1];
public DBManager()
{
//
// TODO: Add constructor logic here
//
// connectionString = System.Configuration.ConfigurationManager.AppSettings.Get("ConnectionString");
}
public static string connectionString
{
get
{
return connStr;
}
set
{
connStr = value;
}
}
public static OdbcConnection getConnection(string connString)
{
try
{
OdbcConnection conn = new OdbcConnection(connString);
conn.Open();
return conn;
}
catch (Exception ex)
{
Log objLog = new Log("getConnection", string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, ex.Message);
LogAs.LogException(objLog);
}
//INSTANT C# NOTE: Inserted the following 'return' since all code paths must return a value in C#:
return null;
}
public static DataTable GetDataTableFromQuery(string strQuery)
{
OdbcConnection myconn = getConnection();
OdbcCommand mycmd = new OdbcCommand();
mycmd.Connection = myconn;
mycmd.CommandType = CommandType.Text;
mycmd.CommandText = strQuery;
OdbcDataAdapter result = new OdbcDataAdapter(mycmd);
//query_found_rows = "select sql_calc_found_rows from
DataSet mydataset = new DataSet();
result.Fill(mydataset);
closeConnection(myconn);
return mydataset.Tables[0]; // make a table
}
public static DataSet GetDataSet(string strQuery)
{
OdbcConnection myconn = getConnection();
OdbcCommand mycmd = new OdbcCommand();
mycmd.Connection = myconn;
mycmd.CommandType = CommandType.Text;
mycmd.CommandText = strQuery;
OdbcDataAdapter result = new OdbcDataAdapter(mycmd);
//query_found_rows = "select sql_calc_found_rows from
DataSet mydataset = new DataSet();
result.Fill(mydataset, "DTCum");
closeConnection(myconn);
return mydataset;
}
public static string GetScalarstring(string query)
{
string str = "";
OdbcConnection myconn = new OdbcConnection();
OdbcCommand mycmd = new OdbcCommand();
try
{
myconn = getConnection();
mycmd.Connection = myconn;
mycmd.CommandType = CommandType.Text;
mycmd.CommandText = query;
str = mycmd.ExecuteScalar().ToString();
}
catch (Exception ex)
{
Log objLog = new Log("GetObjectFromDB", query, string.Empty, string.Empty, string.Empty, string.Empty, ex.Message);
LogAs.LogException(objLog);
return str;
}
finally
{
closeConnection(myconn);
}
return str;
}
public static string GetStringFromByte(object valuegot)
{
string returnstr = Convert.ToString(valuegot);
if (valuegot.GetType().ToString() == "System.Byte[]")
{
returnstr = Encoding.ASCII.GetString((System.Byte[])valuegot);
}
return returnstr;
}
public static ArrayList GetNameValueColl(string query)
{
try
{
OdbcConnection myconn = getConnection();
OdbcCommand mycmd = new OdbcCommand();
mycmd.Connection = myconn;
mycmd.CommandType = CommandType.Text;
mycmd.CommandText = query;
OdbcDataAdapter result = new OdbcDataAdapter(query, myconn);
DataSet mydataset = new DataSet();
result.Fill(mydataset);
closeConnection(myconn);
if (mydataset.Tables.Count > 0)
{
DataTable myTable = mydataset.Tables[0];
//INSTANT C# NOTE: Commented this declaration since looping variables in 'foreach' loops are declared in the 'foreach' header in C#
// DataRow myRow = null;
//INSTANT C# NOTE: Commented this declaration since looping variables in 'foreach' loops are declared in the 'foreach' header in C#
// DataColumn myColumn = null;
string tempkey = null;
string tempval = null;
int lb = 0;
ArrayList myarray = new ArrayList();
foreach (DataRow myRow in myTable.Rows)
{
NameValueCollection tempnvc = new NameValueCollection();
foreach (DataColumn myColumn in myTable.Columns)
{
if (!(myRow[myColumn] == DBNull.Value))
{
tempkey = myColumn.ColumnName;
tempval = GetStringFromByte(myRow[myColumn]);
tempnvc.Add(tempkey, tempval);
}
else
{
tempnvc.Add(myColumn.ColumnName, "");
}
}
myarray.Add(tempnvc);
lb = lb + 1;
}
return myarray;
}
else
{
return null;
}
}
catch (Exception ex)
{
Log objLog = new Log("GetNameValueColl", query, string.Empty, string.Empty, string.Empty, string.Empty, ex.Message);
LogAs.LogException(objLog);
return null;
}
}
public static OdbcConnection getConnection()
{
try
{
//string connstr ="DSN=TRIVIADSN;";
//string connstr = "Driver={MySQL ODBC 3.51 Driver};Server=90.0.0.14;Port=3306;Database=testtrivia;User=root; Password=root;";
string connstr = ConfigurationManager.AppSettings.Get("ConnectionString").ToString();
OdbcConnection conn = new OdbcConnection(connstr);
conn.Open();
return conn;
}
catch (Exception ex)
{
Log objLog = new Log("getConnection", string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, ex.Message);
LogAs.LogException(objLog);
}
//INSTANT C# NOTE: Inserted the following 'return' since all code paths must return a value in C#:
return null;
}
public static void closeConnection(OdbcConnection conn)
{
try
{
conn.Close();
}
catch (Exception ex)
{
Log objLog = new Log("closeConnection", string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, ex.Message);
LogAs.LogException(objLog);
}
}
public static long RunInsertQuery(ESNLib.BaseClass obj)
{
string insertQuery = obj.GetInsertQuery();
return RunQuery(insertQuery, true);
}
public static long RunQuery(string query, bool getLastId)
{
OdbcConnection MyConn = null;
OdbcTransaction tran = null;
long lastid = 0;
try
{
MyConn = DBManager.getConnection();
tran = MyConn.BeginTransaction();
OdbcCommand MyCmd = new OdbcCommand(query, MyConn, tran);
MyCmd.ExecuteNonQuery();
if (getLastId)
{
MyCmd.CommandText = "select LAST_INSERT_ID()";
lastid = Convert.ToInt64(MyCmd.ExecuteScalar());
}
tran.Commit();
return lastid;
}
catch (Exception ex)
{
if (tran != null)
tran.Rollback();
return -1;
}
finally
{
if (MyConn != null)
DBManager.closeConnection(MyConn);
}
}
}
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections;
using System.IO;
using System.Collections.Specialized;
using System.Text;
using System.Data.Odbc;
using ESNAS;
using ESNLib;
public class DBManager
{
public static string connStr;
public static string USATIME = "05:00:00";
// total commands to execute
public static int intCommands = 0;
// the string array with queries
public static string[] QueryCollection = new string[1];
public DBManager()
{
//
// TODO: Add constructor logic here
//
// connectionString = System.Configuration.ConfigurationManager.AppSettings.Get("ConnectionString");
}
public static string connectionString
{
get
{
return connStr;
}
set
{
connStr = value;
}
}
public static OdbcConnection getConnection(string connString)
{
try
{
OdbcConnection conn = new OdbcConnection(connString);
conn.Open();
return conn;
}
catch (Exception ex)
{
Log objLog = new Log("getConnection", string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, ex.Message);
LogAs.LogException(objLog);
}
//INSTANT C# NOTE: Inserted the following 'return' since all code paths must return a value in C#:
return null;
}
public static DataTable GetDataTableFromQuery(string strQuery)
{
OdbcConnection myconn = getConnection();
OdbcCommand mycmd = new OdbcCommand();
mycmd.Connection = myconn;
mycmd.CommandType = CommandType.Text;
mycmd.CommandText = strQuery;
OdbcDataAdapter result = new OdbcDataAdapter(mycmd);
//query_found_rows = "select sql_calc_found_rows from
DataSet mydataset = new DataSet();
result.Fill(mydataset);
closeConnection(myconn);
return mydataset.Tables[0]; // make a table
}
public static DataSet GetDataSet(string strQuery)
{
OdbcConnection myconn = getConnection();
OdbcCommand mycmd = new OdbcCommand();
mycmd.Connection = myconn;
mycmd.CommandType = CommandType.Text;
mycmd.CommandText = strQuery;
OdbcDataAdapter result = new OdbcDataAdapter(mycmd);
//query_found_rows = "select sql_calc_found_rows from
DataSet mydataset = new DataSet();
result.Fill(mydataset, "DTCum");
closeConnection(myconn);
return mydataset;
}
public static string GetScalarstring(string query)
{
string str = "";
OdbcConnection myconn = new OdbcConnection();
OdbcCommand mycmd = new OdbcCommand();
try
{
myconn = getConnection();
mycmd.Connection = myconn;
mycmd.CommandType = CommandType.Text;
mycmd.CommandText = query;
str = mycmd.ExecuteScalar().ToString();
}
catch (Exception ex)
{
Log objLog = new Log("GetObjectFromDB", query, string.Empty, string.Empty, string.Empty, string.Empty, ex.Message);
LogAs.LogException(objLog);
return str;
}
finally
{
closeConnection(myconn);
}
return str;
}
public static string GetStringFromByte(object valuegot)
{
string returnstr = Convert.ToString(valuegot);
if (valuegot.GetType().ToString() == "System.Byte[]")
{
returnstr = Encoding.ASCII.GetString((System.Byte[])valuegot);
}
return returnstr;
}
public static ArrayList GetNameValueColl(string query)
{
try
{
OdbcConnection myconn = getConnection();
OdbcCommand mycmd = new OdbcCommand();
mycmd.Connection = myconn;
mycmd.CommandType = CommandType.Text;
mycmd.CommandText = query;
OdbcDataAdapter result = new OdbcDataAdapter(query, myconn);
DataSet mydataset = new DataSet();
result.Fill(mydataset);
closeConnection(myconn);
if (mydataset.Tables.Count > 0)
{
DataTable myTable = mydataset.Tables[0];
//INSTANT C# NOTE: Commented this declaration since looping variables in 'foreach' loops are declared in the 'foreach' header in C#
// DataRow myRow = null;
//INSTANT C# NOTE: Commented this declaration since looping variables in 'foreach' loops are declared in the 'foreach' header in C#
// DataColumn myColumn = null;
string tempkey = null;
string tempval = null;
int lb = 0;
ArrayList myarray = new ArrayList();
foreach (DataRow myRow in myTable.Rows)
{
NameValueCollection tempnvc = new NameValueCollection();
foreach (DataColumn myColumn in myTable.Columns)
{
if (!(myRow[myColumn] == DBNull.Value))
{
tempkey = myColumn.ColumnName;
tempval = GetStringFromByte(myRow[myColumn]);
tempnvc.Add(tempkey, tempval);
}
else
{
tempnvc.Add(myColumn.ColumnName, "");
}
}
myarray.Add(tempnvc);
lb = lb + 1;
}
return myarray;
}
else
{
return null;
}
}
catch (Exception ex)
{
Log objLog = new Log("GetNameValueColl", query, string.Empty, string.Empty, string.Empty, string.Empty, ex.Message);
LogAs.LogException(objLog);
return null;
}
}
public static OdbcConnection getConnection()
{
try
{
//string connstr ="DSN=TRIVIADSN;";
//string connstr = "Driver={MySQL ODBC 3.51 Driver};Server=90.0.0.14;Port=3306;Database=testtrivia;User=root; Password=root;";
string connstr = ConfigurationManager.AppSettings.Get("ConnectionString").ToString();
OdbcConnection conn = new OdbcConnection(connstr);
conn.Open();
return conn;
}
catch (Exception ex)
{
Log objLog = new Log("getConnection", string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, ex.Message);
LogAs.LogException(objLog);
}
//INSTANT C# NOTE: Inserted the following 'return' since all code paths must return a value in C#:
return null;
}
public static void closeConnection(OdbcConnection conn)
{
try
{
conn.Close();
}
catch (Exception ex)
{
Log objLog = new Log("closeConnection", string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, ex.Message);
LogAs.LogException(objLog);
}
}
public static long RunInsertQuery(ESNLib.BaseClass obj)
{
string insertQuery = obj.GetInsertQuery();
return RunQuery(insertQuery, true);
}
public static long RunQuery(string query, bool getLastId)
{
OdbcConnection MyConn = null;
OdbcTransaction tran = null;
long lastid = 0;
try
{
MyConn = DBManager.getConnection();
tran = MyConn.BeginTransaction();
OdbcCommand MyCmd = new OdbcCommand(query, MyConn, tran);
MyCmd.ExecuteNonQuery();
if (getLastId)
{
MyCmd.CommandText = "select LAST_INSERT_ID()";
lastid = Convert.ToInt64(MyCmd.ExecuteScalar());
}
tran.Commit();
return lastid;
}
catch (Exception ex)
{
if (tran != null)
tran.Rollback();
return -1;
}
finally
{
if (MyConn != null)
DBManager.closeConnection(MyConn);
}
}
}
WCF Function and Database Record Updation
WCF Function in ".aspx" File:
<body>
<form id="form1" runat="server">
************************************************************************
<asp:ScriptManager ScriptMode="Release" LoadScriptsBeforeUI="false" ID="sct" runat="server">
<Services>
<asp:ServiceReference Path="~/wcfServices/Service1.svc" />
</Services>
</asp:ScriptManager>
****************************************************************
<script language="javascript" type="text/javascript">
function changestatus(val)
{
Service1.change_status(val, OnSuccess, OnFailed, "");
return false;
}
function OnSuccess(res) {
if (res != "") {
}
else {
}
}
function OnFailed(res) {
}
</script>
**************************************************************
WCF File:
service1:
<ServiceContract(Namespace:="")> _
<AspNetCompatibilityRequirements(RequirementsMode:=AspNetCompatibilityRequirementsMode.Allowed)> _
Public Class Service1
' Add <WebGet()> attribute to use HTTP GET
<OperationContract()> _
Public Sub DoWork()
' Add your operation implementation here
End Sub
<OperationContract()> _
Public Function change_status(ByVal mid As String) As String
Dim approveqry As String
approveqry = "Update mailbox set status=0 where mailid=" & mid
DBManager.ExecuteNonQuery(approveqry)
Return "read"
End Function
**********************************************************
Call The Function:
server side:
Mail &= " <h3 onclick=" & "'return changestatus(" & dts.Rows(i)("mailid") & ")'" & ">" & dts.Rows(i)("subject") & " <table align='right'><tr><td align='right'> " & dts.Rows(i)("activity") & "</td> </tr></table></h3>"
Mail &= "<div><p>" & dts.Rows(i)("mailcontent") & " </p></div>"
<body>
<form id="form1" runat="server">
************************************************************************
<asp:ScriptManager ScriptMode="Release" LoadScriptsBeforeUI="false" ID="sct" runat="server">
<Services>
<asp:ServiceReference Path="~/wcfServices/Service1.svc" />
</Services>
</asp:ScriptManager>
****************************************************************
<script language="javascript" type="text/javascript">
function changestatus(val)
{
Service1.change_status(val, OnSuccess, OnFailed, "");
return false;
}
function OnSuccess(res) {
if (res != "") {
}
else {
}
}
function OnFailed(res) {
}
</script>
**************************************************************
WCF File:
service1:
<ServiceContract(Namespace:="")> _
<AspNetCompatibilityRequirements(RequirementsMode:=AspNetCompatibilityRequirementsMode.Allowed)> _
Public Class Service1
' Add <WebGet()> attribute to use HTTP GET
<OperationContract()> _
Public Sub DoWork()
' Add your operation implementation here
End Sub
<OperationContract()> _
Public Function change_status(ByVal mid As String) As String
Dim approveqry As String
approveqry = "Update mailbox set status=0 where mailid=" & mid
DBManager.ExecuteNonQuery(approveqry)
Return "read"
End Function
**********************************************************
Call The Function:
server side:
Mail &= " <h3 onclick=" & "'return changestatus(" & dts.Rows(i)("mailid") & ")'" & ">" & dts.Rows(i)("subject") & " <table align='right'><tr><td align='right'> " & dts.Rows(i)("activity") & "</td> </tr></table></h3>"
Mail &= "<div><p>" & dts.Rows(i)("mailcontent") & " </p></div>"
Dynamic Upload Button
Javascript:
function fnAddoption()
{
var Cnt = parseInt(document.getElementById("<%=hiddencount1.ClientID %>").value);
var Cid = parseInt(document.getElementById("<%=hidrowid.ClientID %>").value);
browser = window.navigator.appName;
var newtr;
if (browser == "Microsoft Internet Explorer")
newtr = document.getElementById('Addimg').insertRow();
else
newtr = document.getElementById('Addimg').insertRow(Cid + 1);
var newtd1 = newtr.insertCell(0);
var newtd2 = newtr.insertCell(1);
var newtd4 = newtr.insertCell(2);
var newtd3 = newtr.insertCell(3);
newtd1.innerHTML = "";
newtd2.innerHTML += "<td align='right' width='219'><input class='formTxtBox' style='width:210px; height:20px;' type='file' id='txtGalleryFile" + (Cid) + "' name ='txtGalleryFile" + (Cid) + "' class='txt_box_n' contenteditable='false' value='' onKeyDown='return false;' onKeyPress='return false;' ></td>";
newtd2.height = "";
//newtd2.innerHTML +="<td align='right'>"
newtd4.innerHTML += "<td align='right' width='219'><input type='button' name='btnDel' value=' -' style='height:20px;' onClick=fndel1(this.parentNode.parentNode.rowIndex) >";
newtd4.innerHTML += "<input type='hidden' name='hidImage" + (Cid) + "' id='hidImage" + (Cid) + "' value=''>";
newtd3.innerHTML += "";
document.getElementById("<%=hiddencount1.ClientID %>").value = parseInt(document.getElementById("<%=hiddencount1.ClientID %>").value) + 1;
document.getElementById("<%=hidrowid.ClientID %>").value = parseInt(document.getElementById("<%=hidrowid.ClientID %>").value) + 1;
return true;
}
function fndel1(no, delid)
{
if (delid != undefined) {
document.getElementById('hiddeletIds').value += delid + ",";
}
document.getElementById('Addimg').deleteRow(no);
document.getElementById("<%=hiddencount1.ClientID %>").value = parseInt(document.getElementById("<%=hiddencount1.ClientID %>").value) - 1;
document.getElementById("<%=hidrowid.ClientID %>").value = parseInt(document.getElementById("<%=hidrowid.ClientID %>").value) - 1;
}
Using Page:
<td>
<table cellpadding="0" cellspacing="0" id="Addimg" height="25px" width="200px">
<tr id="trfirst" runat="server">
<td align="center">
<asp:FileUpload ID="imageFileUP" runat="server" Width="219px" />
<td>
<input type="button" id="btnincress" onclick=" return fnAddoption();" runat="server"
style="height: 20px; padding-left: 9px; top: 5px; width: 31px;" value="+" name="btnadd" />
</td>
</td>
</tr>
</table>
<asp:Label runat="Server" ID="lblgalleyFile" Style="float: left;" Height="18px" Width="82px"></asp:Label>
</td>
C# Backend Coding
....................................
#region MultipleUploader
String MultipleUploader()
{
HttpFileCollection Files;
string[] arrCount = null;
Files = Request.Files;
arrCount = Files.AllKeys;
String OldNames = String.Empty;
String ImageFileNames = String.Empty;
string filepath = AppDomain.CurrentDomain.BaseDirectory + "Gallery/";
if (!Directory.Exists(filepath))
{
Directory.CreateDirectory(filepath);
}
try
{
if (System.IO.Path.GetFileName(Files[arrCount[0]].FileName) != "")
{
String tempfile1 = Guid.NewGuid().ToString().Substring(0, 5);
Files[arrCount[0]].SaveAs(filepath + tempfile1 + ".jpg");
ImageFileNames += tempfile1 + ".jpg" + "^";
}
else
{
ImageFileNames += hidrowEditImgFirstRow.Value + "^";
}
}
catch (Exception ex) { }
for (int i = 1; i < arrCount.Length; i++)
{
try
{
String tempname = Guid.NewGuid().ToString().Substring(0, 5);
if (System.IO.Path.GetFileName(Files[arrCount[i]].FileName.Replace("^", "")) != "")
{
Files[arrCount[i]].SaveAs(filepath + tempname + ".jpg");
ImageFileNames += tempname + ".jpg" + "^";
//DBclass.fnThumbImg(filepath, ImageFileNames, "image");
}
else
{
try
{
ImageFileNames += Request.Form["hidImage" + (i - 1)].ToString() + "^";
}
catch (Exception ex)
{
}
}
}
catch (Exception ex)
{
}
}
return ImageFileNames.Substring(0, ImageFileNames.Length - 1);
}
#endregion
File Name:
..........................
string Upload = MultipleUploader();
Javascript Validation
<asp:Button ID="btnsav" class="form_submit" runat="server" Text="Save" OnClick="btnsav_Click1" OnClientClick="return validate()" />
Require field validation:
*********************************************************************************
if (document.getElementById("<%=txtFirstname.ClientID %>").value == "") {
alert("Please enter the first name");
document.getElementById("<%=txtFirstname.ClientID %>").focus()
return false;
}
*******************************************************************************
compare Validation:
if (document.getElementById("<%= hdnOldPassword.ClientID %>").value != "0") {
if (document.getElementById("<%=txtNewPassword.ClientID %>").value != document.getElementById("<%=txtRetypePassword.ClientID %>").value) {
alert("Re-enter password does not match")
document.getElementById("<%=txtNewPassword.ClientID %>").focus()
return false;
}
}
******************************************************************************
Email Validation:
if (document.getElementById("<%=txtEmail.ClientID %>").value=="")
{
alert("Please enter the email");
document.getElementById("<%=txtEmail.ClientID %>").focus()
return false;
}
var exp = /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;
if (!exp.test(document.getElementById("<%=txtEmail.ClientID %>").value)) {
alert("Please enter valid Email");
document.getElementById("<%=txtEmail.ClientID %>").value = "";
document.getElementById("<%=txtEmail.ClientID %>").focus();
return false;
}
*****************************************************************************
Drop down Validation:
if (document.getElementById("<%=ddlMonth.ClientID %>").value == "0") {
alert("Please select the month");
document.getElementById("<%=ddlMonth.ClientID %>").focus()
return false;
}
******************************************************************************
Zip Code Validation:
if (Trim(document.getElementById("<%=txtZip.ClientID%>").value) != "") {
// alert("");
var numberFormat = /^\d{0,15}$/;
if (document.getElementById("<%=txtZip.ClientID%>") != null) {
if (document.getElementById("<%=txtZip.ClientID%>").value != '') {
if (!numberFormat.test(document.getElementById("<%=txtZip.ClientID%>").value)) {
alert('Number Only Allowed.');
document.getElementById("<%=txtZip.ClientID%>").value = '';
document.getElementById("<%=txtZip.ClientID%>").focus();
return false;
}
}
}
var zip = document.getElementById("<%=txtZip.ClientID %>").value;
if (zip.length < "5") {
alert("Zip Code should not be below 5 number");
return false;
}
}
*********************************************************************************
Phone Number Validation:
if (Trim(document.getElementById("<%=txtPhone.ClientID%>").value) != "") {
var objRegExp = /^[1-9]\d{2}-\d{3}-\d{4}$/;
if (objRegExp.test(document.getElementById("<%=txtPhone.ClientID %>").value)) {
}
else {
alert("Please enter the valid phone No.");
document.getElementById("<%=txtPhone.ClientID %>").focus()
return false;
}
}
*********************************************************************************
Check Box Validation:
if (document.getElementById("chkTerms").checked == false) {
alert("Please accept the Terms and Conditions");
document.getElementById("chkTerms").focus()
return false;
}
********************************************************************************
Require field validation:
*********************************************************************************
if (document.getElementById("<%=txtFirstname.ClientID %>").value == "") {
alert("Please enter the first name");
document.getElementById("<%=txtFirstname.ClientID %>").focus()
return false;
}
*******************************************************************************
compare Validation:
if (document.getElementById("<%= hdnOldPassword.ClientID %>").value != "0") {
if (document.getElementById("<%=txtNewPassword.ClientID %>").value != document.getElementById("<%=txtRetypePassword.ClientID %>").value) {
alert("Re-enter password does not match")
document.getElementById("<%=txtNewPassword.ClientID %>").focus()
return false;
}
}
******************************************************************************
Email Validation:
if (document.getElementById("<%=txtEmail.ClientID %>").value=="")
{
alert("Please enter the email");
document.getElementById("<%=txtEmail.ClientID %>").focus()
return false;
}
var exp = /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;
if (!exp.test(document.getElementById("<%=txtEmail.ClientID %>").value)) {
alert("Please enter valid Email");
document.getElementById("<%=txtEmail.ClientID %>").value = "";
document.getElementById("<%=txtEmail.ClientID %>").focus();
return false;
}
*****************************************************************************
Drop down Validation:
if (document.getElementById("<%=ddlMonth.ClientID %>").value == "0") {
alert("Please select the month");
document.getElementById("<%=ddlMonth.ClientID %>").focus()
return false;
}
******************************************************************************
Zip Code Validation:
if (Trim(document.getElementById("<%=txtZip.ClientID%>").value) != "") {
// alert("");
var numberFormat = /^\d{0,15}$/;
if (document.getElementById("<%=txtZip.ClientID%>") != null) {
if (document.getElementById("<%=txtZip.ClientID%>").value != '') {
if (!numberFormat.test(document.getElementById("<%=txtZip.ClientID%>").value)) {
alert('Number Only Allowed.');
document.getElementById("<%=txtZip.ClientID%>").value = '';
document.getElementById("<%=txtZip.ClientID%>").focus();
return false;
}
}
}
var zip = document.getElementById("<%=txtZip.ClientID %>").value;
if (zip.length < "5") {
alert("Zip Code should not be below 5 number");
return false;
}
}
*********************************************************************************
Phone Number Validation:
if (Trim(document.getElementById("<%=txtPhone.ClientID%>").value) != "") {
var objRegExp = /^[1-9]\d{2}-\d{3}-\d{4}$/;
if (objRegExp.test(document.getElementById("<%=txtPhone.ClientID %>").value)) {
}
else {
alert("Please enter the valid phone No.");
document.getElementById("<%=txtPhone.ClientID %>").focus()
return false;
}
}
*********************************************************************************
Check Box Validation:
if (document.getElementById("chkTerms").checked == false) {
alert("Please accept the Terms and Conditions");
document.getElementById("chkTerms").focus()
return false;
}
********************************************************************************
Scramble word in javascript
Scramble Function
function scramble(str)
{
var scrambled = '',
src = str.split(''),
randomNum;
while (src.length > 1)
{
randomNum = Math.floor(Math.random() * src.length);
scrambled += src[randomNum];
src.splice(randomNum, 1);
}
scrambled += src[0];
return scrambled;
}
function scram(txt1,txt2 )
{
txt1.value=scramble(txt2.value);
}
Call the Function In aspx page
<asp:Button ID="Button4" runat="server" CssClass="input" Width="200px" Text="Scramble" OnClientClick="scram(document.getElementById('ctl00_ContentPlaceHolder1_txt_us_scr4'), document.getElementById('ctl00_ContentPlaceHolder1_txt_us_ans4'))" />
function scramble(str)
{
var scrambled = '',
src = str.split(''),
randomNum;
while (src.length > 1)
{
randomNum = Math.floor(Math.random() * src.length);
scrambled += src[randomNum];
src.splice(randomNum, 1);
}
scrambled += src[0];
return scrambled;
}
function scram(txt1,txt2 )
{
txt1.value=scramble(txt2.value);
}
Call the Function In aspx page
<asp:Button ID="Button4" runat="server" CssClass="input" Width="200px" Text="Scramble" OnClientClick="scram(document.getElementById('ctl00_ContentPlaceHolder1_txt_us_scr4'), document.getElementById('ctl00_ContentPlaceHolder1_txt_us_ans4'))" />
Client side validation of File type before you upload a file
To validate a file type or say file extension on client side before you upload a file can be performed by just putting a Regular Expression Validator. Here, i have provided one example to allow uploading only .jpg or .gif files. All you need is a FileUpload control and a Regular Expression Validator to check file type.
<asp:FileUpload ID=”FileUpload1″ runat=”server” />
<asp:RegularExpressionValidator ID=”RegularExpressionValidator1″ runat=”server” ControlToValidate=”FileUpload1″ Display=”Dynamic” ErrorMessage=”Upload a valid file” ValidationExpression=”^.+(.jpg|.JPG|.gif|.GIF)$”></asp:RegularExpressionValidator>
If you want to put your own file type validation then just replace “.jpg,.JPG,.gif,.GIF” text, and you can add more file types by adding “|” (pipe) sign and your own file type to validate.