I want to validate two textboxes on the same asp.net page, each with its corresponding client validation function.
I have one external js file referenced in Head section of asp.net form.
One of the text boxes to be validated is date that works well. That is it displays an error message when an invalid date is entered. But the function for the other text box cannot be invoked.
Here is my asp.net markup:
<asp:CustomValidator ID="CustomValidator2" runat="server"
ClientValidationFunction="validateDate" ControlToValidate="txtdate"
Display="Dynamic" ErrorMessage="CustomValidator" ForeColor="Red"
ValidationGroup="a" onservervalidate="CustomValidator2_ServerValidate">تاریخ نامعتبر</asp:CustomValidator>
<asp:TextBox ID="txtdate" runat="server" Width="120px"></asp:TextBox>
<asp:CustomValidator ID="CustomValidator1" runat="server"
ClientValidationFunction="validatePhoneNumber" ControlToValidate="txtphone"
Display="Dynamic" ErrorMessage="CustomValidator" ForeColor="Red"
onservervalidate="CustomValidator1_ServerValidate1" ValidationGroup="a"
>تلفن نامعتبر</asp:CustomValidator>
<asp:TextBox ID="txtphone" runat="server" Width="120px"></asp:TextBox>
Client validation for date happens but for phone, it does not. By the way, this is my client javascript file's contents:
function validateDate(oSrc, args) {
var iDay, iMonth, iYear;
var arrValues;
arrValues = args.Value.split("/");
iMonth = arrValues[1];
iDay = arrValues[2];
iYear = arrValues[0];
var testDate = new Date(iYear, iMonth - 1, iDay);
if ((testDate.getDate() != iDay) ||
(testDate.getMonth() != iMonth - 1) ||
(testDate.getFullYear() != iYear)) {
args.IsValid = false;
return;
}
return true;
}
function validatePhoneNumber(oSrc, args) {
if (args.Value.Length < 7) args.IsValid = false;
if (isNaN(parseInt(args.value, 10))) args.IsValid = false;
return true;
}
This is too frustrating for me to figure out!
Related
I am migrating my application from IE 9 to IE 11 with compatibility edge mode.
the asp custom validator and required field validator is not working in IE 11, but page.isValid() always returns true. but it works fine in IE 9.
Sample Code:
<asp:DropDownList ID="cboType" onChange="fnInvalid(this,'hidTypeValid');getSelectedValue('cboType','hidliab');changeOptions(document.forms[0].hidliab,document.forms[0].cmbLiability,document.forms[0].hid_liab,document.forms[0].HIDSERLIAB);" runat="server" name="cbotype"AutoPostBack="true"></asp:DropDownList>
<asp:RequiredFieldValidator ID="VreqvalidateType" runat="server" Display="None" ControlToValidate="cboType" ErrorMessage="-Case Type should not be blank" InitialValue="Choose"></asp:RequiredFieldValidator>
<asp:CustomValidator ClientValidationFunction="fnInvalidSelection" ID="VcustTypeValid"
runat="server" Display="None" ControlToValidate="cboType" ErrorMessage="-Case Type should have valid selection."></asp:CustomValidator>
<asp:CustomValidator ClientValidationFunction="fnTypeFileClass" ID="VcusTypeFile" runat="server" Display="None" ControlToValidate="cboType" ErrorMessage="- Case File Classification should not be empty."></asp:CustomValidator>
<asp:CustomValidator Enabled="false"ClientValidationFunction="fnTypeCaseHandler"ID="VcusTypeCaseHandler" runat="server" Display="None" ControlToValidate="cboType"ErrorMessage="- Case Handler 1 should not be empty."></asp:CustomValidator>
Javascript:
<pre lang="C#">function fnTypeCaseHandler(sender,args)
{
var s = args.Value;
args.IsValid = true;
if (s!="K")
{
var handler1= document.frmCaseDetails.cmbHandler1.value;
if (handler1 =="Choose")
{
args.IsValid = false;
}
}
return args.IsValid;
}
function fnTypeFileClass(sender,args)
{
var s = args.Value;
args.IsValid = true;
if (s!="K")
{
var file = document.frmCaseDetails.cmbFileClass.value;
if (file =="Choose")
{
args.IsValid = false;
}
}
return args.IsValid;
}
This is because of an IE-11 Issue we have made<meta> tag with IE-11 compatibility in header section of page its worked well.
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>
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
I tried this code for validating empty field,But it doesn't works properly when call javascript it does not focus on Textbox,and code will execute continues.
Html Code:
<asp:TextBox ID="txtholdername" runat="server" Width="60%"></asp:TextBox>
<asp:TextBox ID="txtusername" runat="server" Width="60%"></asp:TextBox>
<asp:ImageButton ID="btnsave" runat="server" OnClientClick="javascript:return validateRegistrationMaster();" ImageUrl="~/Images/save.png" />
Script
function IsBlank(obj) {
if (obj) {
if (!String.prototype.trim) { String.prototype.trim = function () { return this.replace(/^\s+|\s+$/g, ''); }; }
if ((obj.value.trim().length == 0) || (obj.value == null)) {
obj.focus();
return false;
}
return true;
}
}
function validateRegistrationMaster() {
var Holder_Name = document.getElementById('<%= txtholdername.ClientID %>');
var username = document.getElementById('<%= txtusername.ClientID %>');
if ((!IsBlank(Holder_Name))) {
Holder_Name.focus();
return false;
}
if ((!IsBlank(username))) {
username.focus();
return false;
} return true;
}
Use Required Field Validator instead of custom Javascript, while using Asp.Net Controls.
Example : Click Here W3 Schools Link
Code:
<asp:RequiredFieldValidator ControlToValidate="txtholdername" Text="The holder name field is required!"
runat="server" />
<asp:RequiredFieldValidator ControlToValidate="txtusername" Text="The user namefield is required!"
runat="server" />
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