Validation not working when adding query string - javascript

My validations are not working when redirecting from one page to another on passing query string as a parameter with response.redirect or with windows.location.href.
When I am redirecting from one page to another page with this:
<asp:Button ID="New" runat="server" Text="New" OnClientClick="Transfer()" />
function Transfer() {
window.location.href = "Abc.aspx?flag=yes"; //when adding query string my validation doesnt work
//window.location.href = "Abc.aspx";// When removing query string my validation successfully works
}
Then I have tried from server side like this:
<asp:Button ID="New" runat="server" Text="New" OnClick="New_Click" />
protected void btnNewApplicant_Click(object sender, EventArgs e)
{
Response.Redirect("Abc.aspx?flag=yes", false); //again not working with this.
}
When I click on this New button i am getting error in console:
Is this error has to do anything with this option: EnableEventValidation="false" as you can see in my code?
Note: I need to pass parameter as query string for some reason.
Abc.aspx:
<%# Page Title="" Theme="---" Language="C#" MasterPageFile="---" AutoEventWireup="true" CodeBehind="---" EnableEventValidation="false" Inherits="---" %>
<asp:TextBox ID="txt1" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="rf1" runat="server" ErrorMessage="require" ForeColor="Red" ControlToValidate="txt1" Display="None" ValidationGroup="validate"></asp:RequiredFieldValidator>
<asp:TextBox ID="txt2" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="rf2" runat="server" ErrorMessage="require" ForeColor="Red" ControlToValidate="txt2" Display="None" ValidationGroup="validate"></asp:RequiredFieldValidator>
<asp:Button ID="btnSubmit" runat="server" Text="Save" ValidationGroup="validate" OnClick="btnSubmit_Click" UseSubmitBehavior="true" OnClientClick="checkvalidation()"/> //on click of this i want to perform validation but it is not working.
<telerik:RadCodeBlock ID="radcodeblock1" runat="server" EnableViewState="true">
<script type="text/javascript">
function checkvalidation() {
window.Page_ClientValidate('validate');
var counter= 0;
var val= '';
for (var i = 0; i < window.Page_Validators.length; i++) {
if (!window.Page_Validators[i].isvalid && typeof (window.Page_Validators[i].errormessage) == "string") {
counter= 1;
val+= '- ' + window.Page_Validators[i].errormessage + '<br>';
}
}
if (counter== 1) {
//My validation pop up to display validations alert because this counter value remains 0 so this part is not executed.
}
}
</script>
</telerik:RadCodeBlock>
Now when I click on submit button then my server side code event is fired but my validation pop up doesn't appear.
I have even put this line in web.config:
<add key="ValidationSettings:UnobtrusiveValidationMode" value="None"></add>
But this is still not working as removing query string from response.redirect or from windows.location.href then my validation pop up successfully appears and it is working fine.

If, as you say, window.Page_Validators[i].isvalid is false and typeof (window.Page_Validators[i].errormessage) is true, then we must go into the 'if' condition. The counter must be set to 1, and then must go into the 'if' later on.
I've changed the checks a little bit and have added the console logging to help you. In case anyone doesn't know, you can view these messages by hitting F12 in the browser and clicking "Console".
function checkvalidation() {
window.Page_ClientValidate('validate');
var counter= 0;
var val= '';
for (var i = 0; i < window.Page_Validators.length; i++) {
if ( (window.Page_Validators[i].isvalid === false) && typeof (window.Page_Validators[i].errormessage) == "string") {
console.log("Inside the if condition");
console.log(window.Page_Validators[i]);
counter = 1;
val+= '- ' + window.Page_Validators[i].errormessage + '<br>';
}
}
if (counter === 1) {
//My validation pop up to display validations alert because this counter value remains 0 so this part is not executed.
}
}

Related

Need Client Side Validation for TextBox if '<' and '>' are used in textbox ASP.NET

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>

validate user control input value

How to validate user control textbox value on Parent page? I have the following code but it couldn't find the control. I have checked IE View Source(HTML) and this control renders as
ctl00_Management_Initiation_txtTitle_txtInput
How to get the value using JQuery? Please let me know.
User Control
<telerik:RadTextBox id="txtInput" runat="server" TextMode="MultiLine" LabelCssClass=""></telerik:RadTextBox>
<asp:image id="ImgRequired1" ImageUrl="../../images/requiredfield.gif" AlternateText="Required Field" Runat="server" Visible=false></asp:image><br />
.aspx page
<script type="text/javascript">
$(document).ready(function () {
$("#<%=btnSave.ClientID %>").click(function () {
var valid = true;
var msg = "Please fill form:\n";
if($("input[id*=txtTitle]").val().length == 0{
msg += "Title is Required!\n";
valid = false;
}
});
});
</script>
<uc1:ControlTextBox ID="txtTitle" runat="server" MaxLength="200" ></uc1:ControlTextBox>
<asp:Button ID="btnSave" name="btnSave" runat="server" Text="Save" />
if($("#<%= txtTitle.TextInputClientID %>").val().length == 0) {
There is serious lack of closing brackets, both "}" and ")" in your javascript.
Add property to your user control:
public string TextInputClientID { get { return txtInput.ClientID; } }

Opening ModalPopupExtender Using JavaScript

I have a Popup in my aspx page that i want to open based on criteria that has to be met by javascript. The problem i am having is that i cannot seem to get the modalpopupextender to work no matter what i try.
I have tried using PageMethods, _doPostBack() and $Find(PopupClientId).Show();
None of the above seem to work and i cannot figure out why.
This is my JavaScript.
function RequotePopup(popup, status) {
if (status = true) {
var thePopup = document.getElementById(popup);
thePopup.style.visibility = "visible";
} else {
alert("Please select a record for Re-Quote");
}
}
function checkGridView() {
var hdnCheckboxIDs = document.getElementById("ctl00_ContentPlaceHolder1_hdnCheckboxID");
var arrCheckboxIDs = hdnCheckboxIDs.value.split(",");
var checked = false;
for (var i = 0; i < arrCheckboxIDs.length; i++) {
if (arrCheckboxIDs[i] != "") {
var ckbItem = document.getElementById(arrCheckboxIDs[i]);
if (ckbItem != null) {
if (ckbItem.checked == true) {
checked = true;
}
}
}
}
if (checked == true) {
//var modal = $find('<%= ReQuoteBtn_ModalPopupExtender.ClientID %>');
//modal.show();
PageMethods.ShowExtender();
ShowPopup('RequotePopup');
} else {
alert("Please select a record for Re-Quote");
}
}
And This is my ASP.Net.
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" />
<asp:Button ID="ReQuoteBtn" runat="server" Text="Re-Quote" OnClientClick="Javascript:checkGridView()"
CssClass="Sales" />
<asp:ModalPopupExtender ID="ReQuoteBtn_ModalPopupExtender" runat="server" DynamicServicePath=""
BackgroundCssClass="modalBackground" Enabled="True" BehaviorID="RequoteModal" PopupControlID="RequotePopup"
TargetControlID="ReQuoteBtn" OnCancelScript="cmdCancelrq">
</asp:ModalPopupExtender>
I'm not sure if you have tried this, but it should work if you find the ModalPopupExtender by BehaviorID.
As your BehaviorID is RequoteModal, let try this sample:
To show the popup
$find('RequoteModal').show();
To hide the popup
$find('RequoteModal').hide();
Edit:
I just noticed that you set Enabled="False" for the ModalPopupExtender, this will not allow the modal to call show() method, you may got error message such "Unable to get property 'show' of undefined or null reference".
Please remove that setting and try again.

JavaScript not working with RadTextBox

<telerik:RadCodeBlock ID="RadCodeBlock1" runat="server">
<script type="text/javascript">
function ValidatePhoneNumbers() {
var phone = document.getElementById('txtPhone1');
var mobile =document.getElementById('txtPhone2');
alert(phone.value);
if ((phone.value == null || phone.value == "") && (mobile.value == null || mobile.value == "")) {
alert('something');
return false;
}
else {
alert('something');
return true;
}
}
</script>
<tr>
<td>
<label for="txtPhone1">
Phone :</label>
</td>
<td>
<telerik:RadNumericTextBox ID="txtPhone1" runat="server" Text='<%# Bind("Phone_One") %>' Type="Number" Skin="Windows7" CssClass="txt">
<numberformat allowrounding="false" keepnotroundedvalue="False" GroupSeparator=""></numberformat>
</telerik:RadNumericTextBox>
<asp:CustomValidator ID="rqfldPhone1" runat="server" ControlToValidate="txtPhone1"
Display="Dynamic" ErrorMessage="*" ValidationGroup="Submit" ToolTip="Enter Phone Number" ></asp:CustomValidator>
</td>
<telerik:RadButton ID="btnUpdate" runat="server" Text='<%# (Container is GridEditFormInsertItem) ? "Insert" : "Update" %>'
CommandName='<%# (Container is GridEditFormInsertItem) ? "PerformInsert" : "Update" %>'
Skin="Windows7" ValidationGroup="Submit">
When i add "OnClientClicked" to RadButton to call javaScript ( "return ValidatePhoneNumbers" ) in javaScript It showing NULL WHY ?
there are 2 rad textbox txtphone1 and txtphone2 ,
Actually i want to validate these textbox , if any one is filled no prob otherwise i need to show A error/warning msg.
pls help me
Actually ".value" is not shownig in javascript (document.GetelementById.value)
When you are working with telerik controls the javascript to find controls and do operations is different that of we work with normal html and javascript:
To find radcombox:
$find("<%=RadComboBox1.ClientID %>");//for example
Let work with your problem:
var phone=$find("<%=txtPhone1.ClientID %>");
var mobile=$find("<%=txtPhone2.ClientID %>");
alert(phone.get_value());//use get_value() to get the value of radcombobox
if ((phone.get_value() == null || phone.get_value() == "") && (mobile.get_value() == null || mobile.get_value()== "")) {
alert('something');
eventArgs.set_cancel(true);
}
else {
alert('something');
}
}
The OnClientClicked event will run a function by name with 2 parameters, these are akin to that used by .NET event handlers (sender and eventArgs). The Telerik controls don't cancel the action in the same manner as general HTML objects in that return false; doesn't cancel a post back. Instead, the Telerik API provides a set_cancel() function in the eventArgs parameter.
function ValidatePhoneNumbers(sender, eventArgs) {
var phone = document.getElementById('<%= txtPhone1.ClientId %>'); // Corrected as per my comment
var mobile =document.getElementById('<%= txtPhone2.ClientId %>'); // Corrected as per my comment
alert(phone.value);
if ((phone.value == null || phone.value == "") && (mobile.value == null || mobile.value == "")) {
alert('something');
eventArgs.set_cancel(true);
}
else {
alert('something');
}
}
You don't need to set the OnClientClicked="return ValidatePhoneNumbers" instead I would recomment using OnClientClicking ="ValidatePhoneNumbers" (see: http://www.telerik.com/help/aspnet-ajax/button-onclientclicking.html)
For more information regarding client side event handlers, see: http://demos.telerik.com/aspnet-ajax/menu/examples/programming/clientevents/defaultcs.aspx
The validator should trigger when the button is pressed, if it is not set CausesValidation="True" and maybe consider a RequiredFieldValidator to ensure it is populated before postback.

RadioButtonList checked with javascript

I am trying for a simple validation which consist of a RadioButtonList rblstPallet. I tried the below code:
javascript
var rblstPallet = document.getElementById('rblstPallet');
var counter = 0;
for (var intCount = 0; intCount < rblstPallet.length; intCount++) {
if (rblstPallet[intCount].checked) { //this step is not working
console.log(intCount); //I checked using this step
counter++;
}
}
if (counter == 0) {
//MSG: please select any item
}
else {
// Redirect to next page function
}
.aspx
<asp:RadioButtonList ID="rblstPallet" runat="server" RepeatDirection="Horizontal">
<asp:ListItem>Wood</asp:ListItem>
<asp:ListItem>Plastic</asp:ListItem>
<asp:ListItem>None</asp:ListItem>
</asp:RadioButtonList>
The problem is that if I even select one of the Radio Button, then also the counter value is remaining same. when I debugged the code, I came to know that the line
if (rblstPallet[intCount].checked) {
is not even executing nor even showing any errors in console. I am going through this link. I tried this link(not working).
Please help.
RadioButtoList is converted in radio buttons having id similar to radiobuttonlist id, you need to iterate through DOM to find the matching elements.
function getRadioButtonListSelections(radioButtonListName)
{
int selectionCount = 0;
for(i=0;i<document.forms[0].length;i++)
{
e=document.forms[0].elements[i];
if (e.id.indexOf(radioButtonListName) != -1 && e.checked)
selectionCount++;
}
return selectionCount;
}
alert(getRadioButtonListSelections('rblstPallet'));
Either use:
var rblstPallet = document.getElementById('<%=rblstPallet.ClientID=>');
Or
set the client id mode to static:
<asp:RadioButtonList ID="rblstPallet" runat="server" RepeatDirection="Horizontal" ClientIDMode="static">
And find and loop through each radio button:
var rblstPallet = document.getElementById('rblstPallet');
rblstPallet = rblstPallet.querySelectorAll('input[type="radio"]')
Replace
var rblstPallet = document.getElementById('rblstPallet');
By
var rblstPallet = document.getElementById('<%= rblstPallet.ClientID %>');
If you want to validate your radiobuttonlist why don't you use a validator control ?
<asp:RequiredFieldValidator ID="rfvPallet" runat="server"
ControlToValidate="rblstPallet" ErrorMessage="RequiredFieldValidator">
</asp:RequiredFieldValidator>

Categories