JavaScript not working with RadTextBox - javascript

<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.

Related

Client side validation for Textbox inside Gridview control Using Javascript Or Jquery

I am developing asp.net application, in that i have a page contains gridview with text boxes,
in that i need to validate to fill atleast one text box in that gridview.
I googled many pages, but i have found only check box validation like this,
when save button click, i need to validate to fill atleast one text box in deposit amount in that gridview..
please any answers would be appreciated..
Use RequiredFieldValidator
<asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ControlToValidate="txtAmount" ErrorMessage="Fill This"></asp:RequiredFieldValidator>
<script type="text/javascript">
function validateTextBox() {
//get target base & child control.
var TargetBaseControl = document.getElementById('<%=this.Gridview1.ClientID%>');
var TargetChildControl1 = "txtDepositAmount";
//get all the control of the type INPUT in the base control.
var Inputs = TargetBaseControl.getElementsByTagName("input");
for (var n = 0; n < Inputs.length; ++n)
if (Inputs[n].type == 'text' && Inputs[n].id.indexOf(TargetChildControl1, 0) >= 0)
if (Inputs[n].value != "") return true;
alert('Enter Atleast One Deposit Amount!');
return false;
}
</script>
<asp:ImageButton ID="btnSave" runat="server" ValidationGroup="valInsert" ImageUrl="~/images/save6.png"
Width="40px" Height="40px" OnClientClick="javascript:return validateTextBox();" OnClick="btnSave_Click" ToolTip="Save" />
You can use a CustomValidator and jQuery to check if at least one TextBox has text in it.
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="At least one TextBox is required" ClientValidationFunction="validateMyTextBoxes"></asp:CustomValidator>
<script type="text/javascript">
function validateMyTextBoxes(oSrc, args) {
var isValid = false;
$("#<%= GridView1.ClientID %> input[type=text]").each(function () {
if ($(this).val() != "") {
isValid = true;
}
})
args.IsValid = isValid;
}
</script>

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>

How to validate textbox in gridview when checkbox is checked in same row of gridview using javascript asp.net

i have gridview in my aspx page as
<asp:GridView ID="Grid_FeeCategory" Width="100%" CssClass="table table-striped responsive-utilities jambo_table" runat="server" AutoGenerateColumns="False">
<HeaderStyle CssClass="headings" />
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="checkAll" runat="server" onclick = "checkAll(this);" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkRow" runat="server" onclick = "Check_Click(this)"/>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="CatName" HeaderText="Category" />
<asp:TemplateField HeaderText="Category Fee" HeaderStyle-Width="125px">
<ItemTemplate>
<asp:TextBox ID="txtCatFee" runat="server" placeholder="Int or Decimal" style="width:100%" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="FeeCatID" HeaderText="Category ID" HeaderStyle-CssClass="hidden-field" ItemStyle-CssClass="hidden-field"/>
</Columns>
</asp:GridView>
and my custom validator looks like
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Please enter value"
ClientValidationFunction="Validate" ForeColor="Red"></asp:CustomValidator>
i need to validate textbox in gridview when checkbox in the gridview is checked and user leave textbox empty
e-g if user check the checkbox from row 1 of gridview and also leave textbox empty in row 1 and so on.. then custom validator inform to enter value,
for this i got javascript yesterday from google and manipulate it but it does nothing and here is javascript
<script type="text/javascript">
function Validate(sender, args) {
var gridView = document.getElementById("<%=Grid_FeeCategory.ClientID %>");
var fields= gridView.getElementsByTagName("input");
for (var i = 0; i < fields.length; i++)
{
if (fields[i].type == "fields" && fields[i].checked)
{
if (fields[i].type == "text" && fields[i].value.length < 1)
{
args.IsValid = false;
return;
}
}
}
args.IsValid = true;
}
</script>
i check it by using alerts inside script and it cannot enter into this section of javascript
if (fields[i].type == "text" && fields[i].value.length < 1)
{
args.IsValid = false;
return;
}
It is requirement to do this at client side using javascript so i need your help to get out of it
i know this is late one but any one can get help from following function....
I have example related to your logic. you can do this on client side ...
following code is not exactly your requirement but you can manipulate it according to your requirement .
<script type="text/javascript">
function validate() {
var flag = false;
var gridView = document.getElementById('<%= Grid_FeeCategory.ClientID %>');
for (var i = 1; i < gridView.rows.length; i++) {
var inputs = gridView.rows[i].getElementsByTagName('input');
if (inputs != null && inputs.length > 1 && inputs[0] != null) {
if (inputs[1].type == "text" && inputs[0].type == "checkbox") {
var txtval = inputs[1].value;
if (inputs[0].checked && (txtval == "" || txtval == null)) {
flag = false;
break;
}
else {
flag = true
}
}
}
}
if (!flag) {
new PNotify({
title: 'Error',
text: 'Please provide values for "CHECKED" fee categories....!',
type: 'error',
hide: true
});
}
return flag;
}
</script>
and button where you can call above function
<asp:Button ID="btnCalculate" runat="server"OnClientClick="if(!validate()) { return false;}" OnClick="btnCalculate_Click" Text="Calculate" ValidationGroup="Update"/>
if you need any kind of query to understand then please feel free to ask

Using a custom validator to change a label color if data isn't validated

I am wanting to change the color of a label when its associated text box doesn't pass validation. Not getting any results with my current code:
<asp:Label ID="lblFirstName" runat="server" Text="Your First Name*:"></asp:Label>
<br />
<asp:CustomValidator
ID="customValFirstName"
runat="server"
Text=""
ControlToValidate="txtFirstName"
ClientValidationFunction="validateFirstName"
Display="Dynamic"></asp:CustomValidator>
<asp:TextBox ID="txtFirstName" runat="server" CssClass="textbox" MaxLength="50"></asp:TextBox>
Javascript:
function validateFirstName(sender, args) {
var firstName = document.getElementById('<%=txtFirstName.ClientID %>');
var firstNameLbl = document.getElementById('<%=lblFirstName.ClientID %>');
if (firstName !== "") {
args.IsValid = true;
}
else {
args.IsValid = false;
firstNameLbl.style.color = '#FF0000';
}
};
Any light that can be shed on what I'm doing wrong would be appreciated.
You need to compare the value of the textbox.
Change if (firstName !== "") to if (firstName.value !== "")
Also add one more attribute to your custom validator markup: ValidateEmptyText="true" otherwise empty text won't be validated at all

Multiple conditions not firing in javascript

i am having javascript function written to check if the dropdown value from an aspx page has value "Completed" or "Cancelled".if it is then check if the date and time is not null.
But the function never fires. the code is below.
function EnableValidator() {
var drp = document.getElementById('<%=drpcallstatus.ClientID %>');
var txt = drp.options[drp.selectedIndex].text;
var dt = document.getElementById('<%=txtcompletedate.ClientID %>');
var ct = document.getElementById('<%=txtcomptime.ClientID %>');
if ((txt == "Completed" | txt=="Cancelled") && (dt===null | ct===null)) {
alert("Please Enter the Completed Date and Time");
return false;
}
The function is called from asp.net button
<asp:Button ID="btnsubmit" runat="server" Text="Submit" OnClientClick="return EnableValidator()" onclick="btnsubmit_Click" />
try :
if ((txt == "Completed" || txt=="Cancelled") && (dt===null || ct===null)) {
alert("Please Enter the Completed Date and Time");
return false;
}
You have to use || for it works.
The problem here is that you are not using the correct operator for your OR.
if ((txt == "Completed" || txt=="Cancelled") && (dt===null || ct===null)) {
...
}
Use double pipe characters || for an OR operator in a conditional expression.

Categories