validate user control input value - javascript

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

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>

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

Validation not working when adding query string

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

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

How to send clientid of asp.net control via JavaScript

I am trying to send the control id on button click in my following asp.net code:
<asp:TextBox ID="empid" runat="server" CssClass="input_box" onFocus="if (this.value == this.title) this.value='';" onBlur="if (this.value == '')this.value = this.title;" value="Enter employee ID" title="Enter employee ID" onClick="changecol(this)"></asp:TextBox>
<asp:Button ID="abc" runat="server" Text="xxx"
CssClass="submit_button" onclick="abc_Click" OnClientClick="return checkEmpid('<%=empid.ClientID%>')"/>
and Javascript is:
function checkEmpid(id){
var idValue = document.getElementById(id).value;
alert(idValue);
return false;
}
In alert I am getting null while when I use following code:
<asp:TextBox ID="empid" runat="server" CssClass="input_box" onFocus="if (this.value == this.title) this.value='';" onBlur="if (this.value == '')this.value = this.title;" value="Enter employee ID" title="Enter employee ID" onClick="changecol(this)"></asp:TextBox>
<asp:Button ID="abc" runat="server" Text="xxx"
CssClass="submit_button" onclick="abc_Click" OnClientClick="return checkEmpid()"/>
function checkEmpid(){
var idValue = document.getElementById('<%=empid.ClientID%>').value;
alert(idValue);
return false;
}
In alert I got value entered in text box. Please help me in solving this problem I want to send clientid of control as parameter for JS.
If you definitely want to pass the UserControl name via a parameter, I believe your only option would be to set the function call in the code-behind...
C#...
abc.OnClientClick = string.Format("return checkEmpid('{0}');", empid.ClientID);
VB.NET...
abc.OnClientClick = String.Format("return checkEmpid('{0}');", empid.ClientID)
(Updated, as I realised you wanted the TextBox ID, not the UserControl ID)
You can send client id of empid textbox to javascript this way.
abc.Attributes.Add("onclick", "return checkEmpid('" + empid.ClientID + "')");
function checkEmpid(clientIdOfempid){
alert("This is id of TextField with ID=empid >> "+clientIdOfempid);
return false;
}
or
You can get client ID by '<%=empid.ClientID%>' this way
function checkEmpid(){
var id = '<%=empid.ClientID%>';
alert("This is id of TextField with ID=empid >> "+id);
return false;
}
alert('<%=empid.ClientID%>');
Try this to get ID
Isn't it simplier to alert ID itseld?
alert('<%=empid.ClientID%>');

Categories