Could you please Suggest a client Side Validation for the TextBox in ASP.NET. Needs validation and should not allow user to use '<>'. When text is entered between '<' and '>', it should show validation
You can do this using CustomValidator
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:CustomValidator runat="server" id="customvalidator1" ControlToValidate="TextBox1"
EnableClientScript="true" ErrorMessage="Cannot accept- < or >" ClientValidationFunction="jsvalidate" />
below script should be placed in aspx
<script type="text/javascript">
function jsvalidate(sender, args) {
debugger;
var val = document.getElementById('<%=TextBox1.ClientID%>').value;
if ((val.indexOf('<') !== -1) || (val.indexOf('>') !== -1)) {
alert("Error");
args.IsValid = false;
}
else
{
args.IsValid = true;
}
}
</script>
I want to validate two textboxes on the same asp.net page, each with its corresponding client validation function.
I have one external js file referenced in Head section of asp.net form.
One of the text boxes to be validated is date that works well. That is it displays an error message when an invalid date is entered. But the function for the other text box cannot be invoked.
Here is my asp.net markup:
<asp:CustomValidator ID="CustomValidator2" runat="server"
ClientValidationFunction="validateDate" ControlToValidate="txtdate"
Display="Dynamic" ErrorMessage="CustomValidator" ForeColor="Red"
ValidationGroup="a" onservervalidate="CustomValidator2_ServerValidate">تاریخ نامعتبر</asp:CustomValidator>
<asp:TextBox ID="txtdate" runat="server" Width="120px"></asp:TextBox>
<asp:CustomValidator ID="CustomValidator1" runat="server"
ClientValidationFunction="validatePhoneNumber" ControlToValidate="txtphone"
Display="Dynamic" ErrorMessage="CustomValidator" ForeColor="Red"
onservervalidate="CustomValidator1_ServerValidate1" ValidationGroup="a"
>تلفن نامعتبر</asp:CustomValidator>
<asp:TextBox ID="txtphone" runat="server" Width="120px"></asp:TextBox>
Client validation for date happens but for phone, it does not. By the way, this is my client javascript file's contents:
function validateDate(oSrc, args) {
var iDay, iMonth, iYear;
var arrValues;
arrValues = args.Value.split("/");
iMonth = arrValues[1];
iDay = arrValues[2];
iYear = arrValues[0];
var testDate = new Date(iYear, iMonth - 1, iDay);
if ((testDate.getDate() != iDay) ||
(testDate.getMonth() != iMonth - 1) ||
(testDate.getFullYear() != iYear)) {
args.IsValid = false;
return;
}
return true;
}
function validatePhoneNumber(oSrc, args) {
if (args.Value.Length < 7) args.IsValid = false;
if (isNaN(parseInt(args.value, 10))) args.IsValid = false;
return true;
}
This is too frustrating for me to figure out!
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;
}
I have a textbox and a button, on button's clientClick I call javascript function and there is also server side coding.
Problem is, the page gets post back even if I have return False in the javascript.
Here is my javascript function:
function checkALphaNumericFormat(str) {
//get previous value before editing
var txtUserId = document.getElementById('<%=txtUserId.ClientID%>');
var userId = txtUserId.value;
var patternAlphaNumeric = /^[A-z0-9]+$/gi;
var match = userId.match(patternAlphaNumeric);
//Check Null values
if (txtUserId.value != null && txtUserId.value != "") {
//Check for AlphaNumeric values for User Id
if (match == null) {
alert("Please provide valid AlphaNumeric User Id");
return false ;
}
return false ;
}
else {
alert("User Id field should not be null");
return false ;
}
return false ;
}
and I am calling this function on my Form as:
<asp:Button runat="server" ID="btnCreate" CssClass="loginButton" style="margin:0px 0px 1px 30px;" OnClientClick ="return checkALphaNumericFormat(this.value);" Text="CREATE" />
Try to call JavaScript function as below:
OnClientClick="if(!validateform()){return false;}
where validateform() should be your java script function. Your java script function should have return = true; at the end of function in successfull execution, like in below function:
function validateform()
{
var txtSearch = document.getElementById('<%=txtKeywordSearch.ClientID%>')
if(txtSearch.value == '')
{
alert('No Search Creatria Selected!');
return false;
}
return true;
}
Please try and let me know if it works for you.
Thanks,
Harish
I Have The Following JavaScript Function:
function validateLocality(object, args) {
if (document.getElementById("<%=ddlLocality.ClientID %>").value == "0") {
args.IsValid = false;
}
else {
args.IsValid = true;
}
}
and the following drop down list with validator:
<asp:DropDownList
ID="ddlLocality"
runat="server"
DataSourceID="DataSourceListTowns"
DataTextField="town_name"
DataValueField="town_id"
ToolTip="The Locality Where the User Lives"
AppendDataBoundItems="True"
ViewStateMode="Disabled">
<asp:ListItem Value="0">Select Locality</asp:ListItem></asp:DropDownList>
<asp:CustomValidator
runat="server"
ControlToValidate="ddlLocality"
ErrorMessage="Select Locality"
ToolTip="Select Locality"
ID="validateLocality"
ClientValidationFunction="validateLocality()">*</asp:CustomValidator>
The Thing Is It is not validating the drop-down at all.
Thanks For Any Help Cause I wrecked My Brain about this
The ClientValidationFunction should carry only the name of the function. It is not expecting to carrry a Javascript expression. Hence your attribute should look like: ClientValidationFunction="validateLocality" note no ().
Your function is taking 2 arguments:
function validateLocality(object, args)
But when you call it, you aren't passing any in..?
ClientValidationFunction="validateLocality()"
Add an alert to your function to make sure it's being called on the submit.
function validateLocality(object, args)
{
alert("working");
if (document.getElementById("<%=ddlLocality.ClientID %>").value == "0")
{
args.IsValid = false;
}
else
{
args.IsValid = true;
}
}