I am working on alpha.dubaiexporters.com. There is a search Panel containing two inputs Keyword and Categories. I wanted to validate Keyword part.
If the user entered less than three characters and clicked on Search button then the clientside message should be displayed saying the entered input should be more than 3 characters. I am not getting the clientside message.
The following is my code:
<input type="text" id="txtkeyword" name="s" runat="server" autocomplete="off">
<asp:Button ID="Search" class="dt-header-search-submit dt-button dt-button-danger" style="top:0px;width:226px;height:70px;" Text="Search" runat="server" onclick="doit" OnClientClick="return checkLength();" />
Below is my Javascript:
<script type="text/javascript">
function checkLength() {
var textbox = document.getElementById("txtkeyword");
if (textbox.value.length < 3) {
alert("The entered input should be 3 or more than 3 characters");
return false;
}
}
</script>
Code behind:
protected void doit(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(txtkeyword.Value))
{
try
{
String mainsearch1 = null;
mainsearch1 = txtkeyword.Value.Trim();
if (mainsearch1.Length > 2)
{
Response.Redirect("searchmain.aspx?mainsearch=" + mainsearch1 + "&querylevel=1");
}
}
catch (Exception ex)
{
}
}
else if (!string.IsNullOrEmpty(txtserach.Value))
{
try
{
String cat = null;
cat = txtserach.Value.Trim();
if (cat.Length > 2)
{
Response.Redirect("searchcat1.aspx?cat=" + cat);
}
}
catch (Exception ex)
{
}
}
}
}
I don't know why its not calling javascript function.
Expected output: I want this alert message when user enter less than three letters in txtkeyword textbox.
It works fine, have a try please :)
function checkLength() {
debugger;
var textbox =$get("<%=txtkeyword.ClientID%>"); //document.getElementById("<%=txtkeyword.ClientID%>")
if (textbox.value.length < 3) {
alert("The entered input should be 3 or more than 3 characters");
return false;
}
}
Note: you cant access a control directly when runat="server" is there
Related
The email id is entered into a textbox and the validation for email is applied but there seems to be an error that the whole function is probably not called during execution
<head runat="server">
<title></title>
<script type="text/javascript">
function IsValidUrl()
{
var emailbox = document.getElementById('<%=TextBox4.Text %>');<!--textbox4 is used to receive the email entered by the user-->
var email = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if (textbox.value.length > 0)<!--the email field should be non empty-->
{
if (email.test(emailbox.value))
{
return true;
}
else
{
alert("Please enter valid Email");<!--incase of an invalid email-->
return false;
}
}
else
{
alert("please enter text");
return false;
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:Button ID="Button1" runat="server" style="margin-left: 340px" Text="Submit" Width="96px" OnClick="Button1_Click1" OnClientClick="javascript:IsValidUrl();"/>
</form>
</body>``
There seems couple of issue with the javascript's IsValidURL function so please replace it with below code.
function IsValidUrl()
{
var emailbox = document.getElementById('<%=TextBox4.ID %>');
var email = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if (emailbox.value.length > 0)
{
if (email.test(emailbox.value))
{
return true;
}
else
{
alert("Please enter valid Email");
return false;
}
}
else
{
alert("please enter text");
return false;
}
}
There are mainly two problems
<%=TextBox4.Text %> here you want id of the textBox but you are fetching value of the textBox.
textbox.value.length you want to check value of the TextBox4 but its variable name is emailbox, not textbox.
So I have just corrected those.
Hope this helps you.
Probably your function is working correctly but the page gets submitted even after the validation so replace below:
OnClientClick="javascript:IsValidUrl();"
with
OnClientClick="return javascript:IsValidUrl();"
Edit
Just figured an error in your JS code if (textbox.value.length > 0) line should be if (emailbox.value.length > 0) so try with replace it.
Another issue I found in document.getElementById('<%=TextBox4.Text %>') which should be document.getElementById('<%=TextBox4.ID %>') and in case of using master pages it should be document.getElementById('<%=TextBox4.ClientID %>') so try replacing it too.
Hope this will help !!
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/
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
prevent postback of HtmlButton in C#
Here's my JavaScript function:
<script type = "text/javascript">
function CheckForEmptySearchBox(id) {
var index = id.substring(id.length - 1);
var boxContent = document.getElementById("contentMain__lvTSEntry__txtClientName_" + index).value;
if (boxContent == "") {
alert("Please enter search criteria");
return false;
}
}
</script>
And the markup:
<asp:Button ID="_btnSearch" runat="server" OnClientClick = "return CheckForEmptySearchBox(this.id)" />
This code is working, i.e. when the texbox is empty, the message prompt the user to enter search criteria and the javascript prevents the page to postback. However, when the user enters text, there's no message prompt but the page still doesn't postback. What's wrong?
EDIT
if (boxContent == "") {
alert("Please enter search criteria");
return false;
}
else {
return true;
}
The page is still not posting back.
you need to return true from your function if you mean it to return true....
<script type = "text/javascript">
function CheckForEmptySearchBox(id) {
var index = id.substring(id.length - 1);
var boxContent = document.getElementById("contentMain__lvTSEntry__txtClientName_" + index).value;
if (boxContent == "") {
alert("Please enter search criteria");
return false;
}
else{ return true;}
}
you are asking for a return onclientclick function and not returning any value when textbox having value that`s why its stuck
<asp:Button ID="_btnSearch" runat="server" OnClientClick = "return CheckForEmptySearchBox(this.id)" />
You are forgetting to return true if the validation passes:
function CheckForEmptySearchBox(id) {
var index = id.substring(id.length - 1);
var boxContent = document.getElementById("contentMain__lvTSEntry__txtClientName_" + index).value;
if (boxContent == "") {
alert("Please enter search criteria");
return false;
}
return true; //<--you forgot this
}
I am validating a form from javascript.
The target is: if user do not enter value in a required field, an error message will show up and will disappear after few seconds.
BUT
The problem is: The error message don't show up and this is probably because from javascript I am failing to write error message in a label control. BUT, if I use javascript alert instead of displaying the label, it works.
The code:
Javascript
<script type="text/javascript">
function showConfirmation() {
$('div#confirmationDV').show();
setTimeout(function () {
$('div#confirmationDV').fadeOut(5000);
});
}
function validateRequiredField() {
if (document.getElementById("<%=txtOfferTitle.ClientID%>").value == "") {
alert("error.....");//this alert works.
document.all("<%=lblConfirmation.ClientID%>").innerHTML = "please enter your business name"; // this does not work
document.all("<%=lblConfirmation.ClientID%>").style.color = "red";
showConfirmation();
document.getElementById("<%=txtOfferTitle.ClientID%>").focus();
return false;
}
return true;
}
</script>
HTML
<div class="round-conf-box" id="confirmationDV">
<div class="round-conf-tl">
<div class="round-conf-tr"></div>
<div class="round-conf-background_color_top"></div>
</div>
<div class="round-conf-box-Content">
<asp:Label ID="lblConfirmation" runat="server" CssClass="confirmationLabel"></asp:Label>
</div>
<div class="round-conf-bl">
<div class="round-conf-br"></div>
<div class="round-conf-background_color_bottom"></div>
</div>
//...some other stuff
<asp:ImageButton ID="iBtnSave" runat="server" ImageUrl="~/images/createOffer.png"
onclick="iBtnSave_Click" OnClientClick="return validateRequiredField()" />
and in the code behind
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
iBtnSave.Attributes.Add("onclick", "return validateRequiredField()");
//some other stuff
}}
Would be nice if anyone can help me to find my mistakes..
cheers
You mix jQuery and IE-Only JScript.
Make sure to only use jQuery or cross browser JavaScript
Change
function validateRequiredField() {
if (document.getElementById("<%=txtOfferTitle.ClientID%>").value == "") {
alert("error.....");
document.all("<%=lblConfirmation.ClientID%>").innerHTML = "please enter your business name";
document.all("<%=lblConfirmation.ClientID%>").style.color = "red";
showConfirmation();
document.getElementById("<%=txtOfferTitle.ClientID%>").focus();
return false;
}
return true;
}
to
$("#<%=iBtnSave.ClientID%>).click(function(e) {
var txtOffer = $("#<%=txtOfferTitle.ClientID%>");
var txtOfferLbl = $("#<%=lblConfirmation.ClientID%>");
if (txtOffer.val() == "") {
alert("error.....");
txtOfferLbl.text("please enter your business name");
txtOfferLbl.addClass("error");
showConfirmation();
txtOffer.focus();
e.preventDefault();
}
else {
txtOfferLbl.text("");
txtOfferLbl.removeClass("error");
}
});