Validating with JavaScript Function - javascript

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;
}
}

Related

ASP Web Forms fire code behind event on condition

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"))
{
}
}

ASP serverside validation shows not valid and clientside validation shows valid?

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;

Stop postback after alert by javascript in ASP.NET Code

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

Checkbox won't change value with javascript

I have 2 check boxes where only one or none may be checked.
Since I can't do a postback I tried this with Javascript.
The Javascript finds the element (tested it with an alert).
But the value won't change.
Any Idea how I can do this with Javascript?
The Javascript:
function mrcAndNbbFilterChanged(mrcOrNbb)
{
alert("er in");
if(mrcOrNbb == 0)
{
document.getElementById("ctl00_contentHolder_cb_mrcFilter").checked=true;
document.getElementById("ctl00_contentHolder_cbNoBackBilling").checked=false;
alert(document.getElementById("ctl00_contentHolder_cbNoBackBilling"));
alert("0");
}
else
{
if(mrcOrNbb == 1)
{
alert("1");
document.getElementById("cb_mrcFilter").checked=false;
document.getElementById("cbNoBackBilling").checked=true;
}
}
}
The ASP code:
<asp:CheckBox ID="cb_mrcFilter" runat="server" Text="Only MRC" OnClick="mrcAndNbbFilterChanged(0)" />
<asp:CheckBox ID="cbNoBackBilling" runat="server" Text="No back billing" OnClick="mrcAndNbbFilterChanged(1)" />
ASP.NET applies that ctl00_-esque string to IDs when using ASP controls to ensure they are unique. You can get the ASP-modified ID value using:
document.getElementById("<%= cb_mrcFilter.ClientID %>").checked=false;
document.getElementById("<%= cbNoBackBilling.ClientID %>").checked=true;
Also, as a side note, you can use else if { ... }, rather than else { if { ... } } when only dealing with one alternative:
if(mrcOrNbb == 0) {
...
}
else if(mrcOrNbb == 1) {
...
}

JavaScript not firing in ASP.NET

function isGoodEmail() {
var email = document.getElementById("<%=txtComapnyEmail.ClientID%>").value;
if (email == "Email") {
if (window.isValidEmail(email)) {
if (/(aol|gmail|yahoo|hotmail)\.com$/.test(email)) {
alert(' valid email, but not for this site. No free service emails!');
return false;
}
return true;
}
return false;
}
Button code:
<asp:Button runat="server" class="button-orange" Text="Confirm and start my company page"
ID="Companystart" OnClick="CompanystartClick" OnClientClick="isGoodEmail" />
I am calling the above JavaScript from the button, but it is not validating the email. Even if entered gmail it is accepted.
use the following
<asp:Button runat="server" class="button-orange" Text="Confirm and start my company page"
ID="Companystart" OnClick="CompanystartClick" OnClientClick="return isGoodEmail()" />
Your are missing 'return' before your client click function call OnClientClick="return isGoodEmail()"
As you have written return true and false in your java-script so in your function call too there should be return before the function name.
For better understanding of return true and false you can go through this link
What's the effect of adding 'return false' to a click event listener?
---EDIT
function isGoodEmail() {
alert("In the beginning");
var email = document.getElementById("<%=txtComapnyEmail.ClientID%>").value;
alert(email);
if (email == "Email") {
if (window.isValidEmail(email)) {
if (/(aol|gmail|yahoo|hotmail)\.com$/.test(email)) {
alert(' valid email, but not for this site. No free service emails!');
return false;
}
return true;
}
return false;
}
If you put OnClientClick="return isGoodEmail()" it will work it invokes JavaScript code.
but suppose you put "gmail" as text for email, then the if condition
if (email == "Email")
is false so nothing is executed inside or returned
hence it feels like JavaScript is not invoked
try using firebug to debug and break-point js code

Categories