In my NIC textbox I am trying to do validation where the first letter of the NIC text value need to be the same as the first letter of the last name text value.
Last Name Textbox
<div class="form-group row justify-content-center mt-2">
<asp:Label ID="lblLName" CssClass="col-md-2 col-form-label" runat="server" Text="Last Name"></asp:Label>
<div class="col-md-4">
<asp:TextBox ID="txtLName" CssClass="form-control" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="revLname"
runat="server"
Display="Dynamic"
ForeColor="Red"
ControlToValidate="txtLName"
ValidationExpression="([A-Z][a-z]+)$"
SetFocusOnError="true"
ErrorMessage="Invalid Fname"></asp:RegularExpressionValidator>
<asp:RequiredFieldValidator
ID="rfvLname"
runat="server"
Display="Dynamic"
ForeColor="Red"
ControlToValidate="txtLName"
SetFocusOnError="true"
ErrorMessage="Last Name is Mandatory"></asp:RequiredFieldValidator>
</div>
</div>
NIC textbox
<div class="form-group row justify-content-center mt-2">
<asp:Label ID="lblNic" CssClass="col-md-2 col-form-label" runat="server" Text="NIC"></asp:Label>
<div class="col-md-4">
<asp:TextBox ID="txtNIC" CssClass="form-control" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator
ID="rfvNic"
runat="server"
Display="Dynamic"
ForeColor="Red"
ControlToValidate="txtNIC"
SetFocusOnError="true"
ErrorMessage="NIC is Mandatory"></asp:RequiredFieldValidator>
<asp:CustomValidator
ID="cvNic"
runat="server"
OnServerValidate="cvNic_ServerValidate"
ClientValidationFunction="validateLength"
Display="Dynamic"
ForeColor="Red"
ControlToValidate="txtNIC"
SetFocusOnError="true"
ErrorMessage="Invalid NIC"></asp:CustomValidator>
<asp:RegularExpressionValidator
ID="revNic"
runat="server"
ValidationExpression="^[a-zA-Z0-9\s]{14}$"
Display="Dynamic"
ForeColor="Red"
ControlToValidate="txtNIC"
SetFocusOnError="true"
ErrorMessage="Must contain 14 characters"></asp:RegularExpressionValidator>
</div>
</div>
I made a Custom Validation server and client side:
server Side
protected void cvNic_ServerValidate(object source, ServerValidateEventArgs args)
{
if (txtLName.Text != string.Empty)
{
String lletter = txtLName.Text.ToLower();
string firstletter = lletter[0].ToString();
String nic = txtNIC.Text.ToLower();
String nfletter = nic[0].ToString();
if (nfletter != firstletter)
{
args.IsValid = false;
}
}
}
Client Side
function validateLength(sender, args) {
var LastName = document.getElementById['txtLName'].value;
var Nic = document.getElementById['txtNIC'].value;
if (LastName !== null || LastName !== '') {
var lletter = LastName.toLowerCase;
var firstletter = lletter.substr(1, 1);
var nic = Nic.toLowerCase;
var nfletter = nic.substr(1, 1);
if (nfletter != firstletter) {
return args.IsValid = false;
}
}
I have made a condition that in order for this validation to occur, it should verify if the last name textbox is not empty then if it is, it extract both textbox first letters and compare it in a if statement.
The problem is when I click submit the validation of the client side is not functioning and for the server side ,the validation is functioning after the data has been send.
How can I tackle this please?
I would use a CustomValidator for this that checks if txtLName is not empty and then compares the first letters. PS to get the first letter with substr you need to start at index 0.
<asp:CustomValidator runat="server" ID="CustomCompareValidator"
ClientValidationFunction="CustomCompareValidator"
ErrorMessage="The first letters should match"></asp:CustomValidator>
The javascript
<script>
function CustomCompareValidator(source, args) {
var $txtNIC = $('#<%= txtNIC.ClientID %>');
var $txtLName = $('#<%= txtLName.ClientID %>');
// or use $('#txtNIC') & $('#txtLName') is you want to use the script
// in a separate js file
//check if lastname is not empty
if ($txtLName.val() !== '') {
//check if the first letters match
if ($txtLName.val().substr(0, 1) !== $txtNIC.val().substr(0, 1)) {
args.IsValid = false;
return;
}
}
args.IsValid = true;
}
</script>
Related
I have a User Control with a Datagrid. I need to check some Textboxes within by calling my Javascript File doing the compare when the user will Save its modifications. (it will trigger my validator, if it is wrong a popup will show)
My ASPX:
<script type="text/javascript" src='/scripts/production_cost.js'></script>
<ContentTemplate>
<asp:DataGrid ID="ProdCostGrid" runat="server" AutoGenerateColumns="False" BorderColor="#f0f0f0" BorderStyle="None" BorderWidth="0px" CellPadding="0">
<HeaderStyle HorizontalAlign="Center"></HeaderStyle>
<Columns>
<asp:BoundColumn Visible="False" DataField="Id" HeaderText="Id"></asp:BoundColumn>
<asp:TemplateColumn>
<ItemTemplate>
Amount: <asp:TextBox ID="ProductionCostLineField" Text='<%# ToText(Eval("ProductionCostEuro")) %>'
TabIndex="24" runat="server" Width="80px" MaxLength="13"></asp:TextBox> EUR
</ItemTemplate>
<ItemStyle Width="170px" HorizontalAlign="Right"></ItemStyle>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>
//here I am suppose to put my Validator
<asp:CustomValidator ID="AmountCustomValidator" runat="server" Display="None" ErrorMessage="Amount must be filled" ClientValidationFunction="ValidateAmount" />
</ContentTemplate>
My Javascript in a different folder :
function ValidateAmount(source, args) {
args.IsValid = true;
$('input[id*="ProductionCostLineField"]').blur(function () {
var amount = this.value;
$('input[id*="ProductionCostInvoiceToLineField"]').each(function () {
var textInvoicedBy = this.value;
if (amount == '' || amount == '0') {
} else {
if (this.value != '' || amount == '' || amount == '0') {
args.IsValid = true;
}
if ((amount != '' || amount != '0') && textInvoicedBy == '') {
alert("You must inform the field 'Invoiced By'");
args.IsValid = false;
}
}
});
});
}
Here's my JavaScript code: it's not working
<script language="javascript" type="text/javascript">
function ShowExpenseReport(Expense_Report_ID) {
var width = screen.width;
var leftpad = (width - 740) / 2;
var jsoption = "width=740,height=700,resizable=no,scrollbars=yes,toolbar=no,titlebar=no,location=no,directories=no,status=no,menubar=no,copyhistory=no,left=" + leftpad + ",top=10";
window.open("Documents/ExpenseReport.aspx?Expense_Report_ID=" + Expense_Report_ID, 'win02', jsoption);
return false;
}
function changetextbox() {
if (document.getElementById("ddlItem").value == '3') {
document.getElementById("txtPurpose").disabled = 'true';
} else {
document.getElementById("txtPurpose").disabled = '';
}
}
</script>
Below is the HTML side:
<asp:TemplateField HeaderStyle-CssClass="innerGridHeader" ItemStyle-CssClass="itemPadding"
ItemStyle-Width="150px" HeaderStyle-VerticalAlign="Top" FooterStyle-VerticalAlign="Top">
<HeaderTemplate>
Item
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblItem" Visible="false" runat="server" Text='<%#Eval("Item_Description") %>'></asp:Label>
<asp:Label ID="lblItemID" Visible="false" runat="server" Text='<%#Eval("Item_ID") %>'></asp:Label>
<asp:DropDownList ID="ddlItem" Width="140px" runat="server" onChange="changetextbox()" CssClass="combobox">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-CssClass="innerGridHeader" ItemStyle-CssClass="itemPadding"
ItemStyle-Width="260px" HeaderStyle-VerticalAlign="Top" FooterStyle-VerticalAlign="Top">
<HeaderTemplate>
Purpose
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblPurpose" runat="server" Width="240px" Text='<%#Eval("Purpose") %>'></asp:Label>
<asp:TextBox ID="txtPurpose" runat="server" Width="240px" CssClass="inputbox" Text='<%#Eval("Purpose") %>'></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvPurpose" runat="server" ErrorMessage="Enter Purpose"
ControlToValidate="txtPurpose" Display="None" ValidationGroup="NER" SetFocusOnError="True">
</asp:RequiredFieldValidator>
<asp:ValidatorCalloutExtender ID="vcePurpose" runat="server" TargetControlID="rfvPurpose"
PopupPosition="BottomRight" WarningIconImageUrl="~/Library/Images/exclamation.png" />
</ItemTemplate>
</asp:TemplateField>
I just want to disable the textboxes when the user chooses entertainment from the dropdown which has the value 3 in the database.
I believe what you are trying to do is disable/enable a textbox field on the basis of select value. A proper way followed in ASP is as follows, try this:
onchange="DisableTextBox();"
<script language=javascript>
function DisableTextBox() {
var dropDown = document.getElementById('<%=DropDown.ClientID%>');
if (dropDown.selectedIndex = ValueTocompare) {
document.getElementById('<%=txtBoxID.ClientID%>').disabled = disabled;
} else {
document.getElementById('<%=txtBoxID.ClientID%>').disabled = '';
}
}
</script>
if this doesn't work out for you, try using this fiddle:
http://jsfiddle.net/SurajMindfire/zxvfcvq0/
This will help you:
dropdown is there contain YES and No value(by default yes),
there is text box, when user select YES value from dropdown textbox will enabled but when select No value then textbox get desabled.
astric is id for validation of textbox
function EnableDisableInputField(customerNarration) {
var selectedValue = customerNarration.options[customerNarration.selectedIndex].value;
var txtOther = document.getElementById("customisedNarration");
txtOther.disabled = selectedValue == 'N' ? true : false;
document.getElementById("asterisk").innerHTML = "";
if (!txtOther.disabled) {
txtOther.focus();
document.getElementById("asterisk").innerHTML = "*";
}
var checkError = document.getElementById("customisedNarration_box").style = "display: none";
}
<div class="form-group ">
<label class="floatinglabel"><sup class="text-red">*</sup> Customer Narration required</label>
<div class="selectwrapper">
<select class="form-control" id="customerNarration" name="customerNarration" onchange="EnableDisableInputField(this)" onfocus="hideerrmsgdelayed('customerNarration')">
<option value="Y">Yes</option>
<option value="N">No</option>
</select>
</div>
<span class="inputError" id="customerNarrationReq_box"><%=siteValidation.getErrorMessage("customerNarration")%></span>
</div>
<div class="form-group ">
<label class="floatinglabel"><sup class="text-red" id="asterisk"></sup> Customised Narration </label>
<input type="text" class="form-control" name="customisedNarration" id="customisedNarration" onfocus="hideerrmsgdelayed('customisedNarration')" maxlength="50" />
<span class="inputError" id="customisedNarration_box"><%=siteValidation.getErrorMessage("customisedNarration")%></span>
</div>
Guys I have a form like this(an aspx page): http://prntscr.com/8tmvge . I wrote validations each of them,And it is working properly. If user enter numeric value in name textbox (ex),it gives error and I'm clearing that textbox(only that textbox) but enter the accurate value and pressing send button, none of the validations and click events doesn't triggered.I couldn't understand how can I fix this? code is below:
Ekle.aspx:
<form id="form1" runat="server">
<div id="ekle">
<asp:Table ID="Table1" runat="server">
<asp:TableRow ID="TableRow1" runat="server">
<asp:TableCell>Id:</asp:TableCell>
<asp:TableCell>
<asp:TextBox ID="txt1" runat="server" ></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txt1" />
</asp:TableCell>
</asp:TableRow>
<asp:TableRow ID="TableRow2" runat="server">
<asp:TableCell>Name:</asp:TableCell><asp:TableCell>
<asp:TextBox ID="txt2" runat="server" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="txt2" />
</asp:TableCell>
</asp:TableRow>
<asp:TableRow ID="TableRow3" runat="server">
<asp:TableCell>Surname:</asp:TableCell><asp:TableCell>
<asp:TextBox ID="txt3" runat="server"/>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="txt3" />
</asp:TableCell>
</asp:TableRow>
<asp:TableRow ID="TableRow4" runat="server">
<asp:TableCell>Sex:</asp:TableCell>
<asp:TableCell>
<span id="spanddl">
<asp:DropDownList ID="ddl1" runat="server">
<asp:ListItem Value="Bay">Bay</asp:ListItem>
<asp:ListItem Value="Bayan">Bayan</asp:ListItem>
</asp:DropDownList>
</span>
</asp:TableCell>
</asp:TableRow>
<asp:TableRow ID="TableRow5" runat="server">
<asp:TableCell>Email:</asp:TableCell><asp:TableCell>
<asp:TextBox ID="txt5" runat="server" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ControlToValidate="txt5" />
</asp:TableCell>
</asp:TableRow>
<asp:TableRow ID="TableRow6" runat="server">
<asp:TableCell>City:</asp:TableCell><asp:TableCell>
<asp:TextBox ID="txt6" runat="server" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server" ControlToValidate="txt6" />
</asp:TableCell>
</asp:TableRow>
<asp:TableRow ID="TableRow7" runat="server">
<asp:TableCell>Age:</asp:TableCell>
<asp:TableCell>
<asp:TextBox ID="txt7" runat="server" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator6" runat="server" ControlToValidate="txt7" />
</asp:TableCell>
</asp:TableRow>
<asp:TableRow>
<asp:TableCell>
<input id="ekle_gonder" type="button" value="Gönder" />
</asp:TableCell>
</asp:TableRow>
</asp:Table>
</div>
</form>
ekle.js :
$(document).ready(function () {
var result = 1;
var id, name, surname, email, city, age;
$("#content").on('click', "#ekle_gonder", function (e) {
var gender = $("#ddl1 option:selected").text();
//var gender = document.getElementById('<%= ddl1.ClientID%>');
//var gender2 = gender.options[gender.selectedIndex].value;
check();
var obj = {};
obj.Id = id;
obj.Name = name;
obj.Surname = surname;
obj.Sex = gender;
obj.Email = email;
obj.City = city;
obj.Age = age;
if (result == 1) {
$.ajax({
type: "post",
url: "ShowRecord.aspx/ekle_func",
contentType: "application/json;charset:utf-8",
data: JSON.stringify(obj),
dataType: "json",
success: onSuccess,
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
//complete:printAgain()
});
}
});
function check() {
var mailregex = /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+#[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
var textregex = /^[A-Za-z çğıöşü]{1,25}$/;
var numregex = /(^\d+$)/;
id = $("#txt1").val();
name = $("#txt2").val();
surname = $("#txt3").val();
email = $("#txt5").val();
city = $("#txt6").val();
age = $("#txt7").val();
if ((numregex.test(parseInt(id)) == false) || (parseInt(id) < 0)) {
open_error_box("#ekle_id_error", "#txt1");
}
if ((name == '') || (textregex.test(name) == false)) {
open_error_box("#ekle_name_error", "#txt2");
}
if ((surname == '') || (textregex.test(surname) == false)) {
open_error_box("#ekle_surname_error", "#txt3");
}
if ((email == '') || (mailregex.test(email) == false)) {
open_error_box("#ekle_email_error", "#txt5");
}
if ((city == '') || (textregex.test(city) == false)) {
open_error_box("#ekle_city_error", "#txt6");
}
if ((numregex.test(parseInt(age)) == false) || (parseInt(age) < 0) || (parseInt(age) > 100)) {
open_error_box("#ekle_age_error", "#txt7");
}
return result;
}
function open_error_box(error_name, name) {
$(error_name).dialog("open");
$(name).val('');
result = 0;
}
function onSuccess() {
$("#txt1").val('');
$("#txt2").val('');
$("#txt3").val('');
$("#txt4").val('');
$("#txt5").val('');
$("#txt6").val('');
$("#txt7").val('');
}
$(function () {
$("#ekle").dialog();
$("#ekle_id_error ,#ekle_name_error, #ekle_surname_error, #ekle_email_error, #ekle_city_error, #ekle_age_error").dialog(
{
autoOpen: false,
buttons: [{
text: "OK",
click: function () { $(this).dialog("close"); }
}]
});
});
});
By the way the id='content' selector is in another page.I'm loading Ekle.aspx into a div(in ShowRecord.aspx) when pressed 'ekle' button(inside ShowRecord.aspx again).ANd error dialog boxes are in ShowRecord.aspx also.
When you clear the textbox, you should change the result value as 1. Your result value just set as 1, when the document is ready. However, if there is something is wrong, you set it as 0, then you never change it as 1.
I am validating some .net textboxes in javascript on focusout via regular expression:
ValidationExpression="[0-9]+(\.[0-9][0-9]?)?"
for all text boxes.
If isValidate, button enabled = true else button enabled = false
but my code doesn't work:
<dx:ASPxTextBox ID="tbxAcPart" runat="server" Width="95px" ClientIDMode="Static">
<ClientSideEvents Validation="function(s, e) {ValidTextBox(s);}" />
<ValidationSettings ErrorDisplayMode="Text" EnableCustomValidation="true" SetFocusOnError="true" ValidationGroup="Apply" Display="Dynamic" ErrorTextPosition="Bottom" >
<ErrorFrameStyle Font-Size="Smaller"/>
<RegularExpression ValidationExpression="[0-9]+(\.[0-9][0-9]?)?" ErrorText="Numeric !" />
<RequiredField IsRequired="true" />
</ValidationSettings>
</dx:ASPxTextBox>
<dx:ASPxTextBox ID="tbxMpPart" runat="server" Width="95px" ClientIDMode="Static">
<ClientSideEvents Validation="function(s, e) {ValidTextBox(s);}" />
<ValidationSettings ErrorDisplayMode="Text" EnableCustomValidation="true" SetFocusOnError="true" ValidationGroup="Apply" Display="Dynamic" ErrorTextPosition="Bottom" >
<ErrorFrameStyle Font-Size="Smaller"/>
<RegularExpression ValidationExpression="[0-9]+(\.[0-9][0-9]?)?" ErrorText="Numeric !" />
<RequiredField IsRequired="true" />
</ValidationSettings>
</dx:ASPxTextBox>
function ValidTextBox(s) {
if (s.GetIsValid()) {
decimalErr.SetText('');
}
else {
decimalErr.SetText(s.GetErrorText());
var t = document.getElementsById("btApply");
t.disabled = true;
this.focus();
}
}
If you use server control you need to use ctl.ClientID
function ValidTextBox(s) {
if (s.GetIsValid()) {
decimalErr.SetText('');
}
else {
decimalErr.SetText(s.GetErrorText());
var t = document.getElementById("<%= btApply.ClientID %>");
t.disabled = true;
this.focus
}
}
I am calculating the total of GridView cells using java script and jquery. But, I am always getting this error while compiling.
The name 'total' does not exist in the
current context
Inside GridView code:
<asp:TemplateField HeaderText="Header 1">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="lblTotal" runat="server" Text="Total" Font-Bold="true">
</asp:Label>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Header 2" >
<ItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" class="calculate"
onchange="calculate()"></asp:TextBox>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="total" runat="server"></asp:TextBox>
</FooterTemplate>
javascript and jquery code:
<script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js"
type="text/javascript">
<script language="javascript" type="text/javascript">
function calculate()
{
var txtTotal = 0.00;
//var passed = false;
//var id = 0;
$(".calculate").each(function (index, value) {
var val = value.value;
val = val.replace(",", ".");
txtTotal = MathRound(parseFloat(txtTotal) + parseFloat(val));
});
document.getElementById("<%=total.ClientID %>").value = txtTotal.toFixed(2);
}
function MathRound(number) {
return Math.round(number * 100) / 100;
}
</script>
how can I solve this issue any help pls.
You can't access controls inside templated controls like GridView that easily. Create some variable to hold total.ClientID so that jQuery can grab it.
In your aspx:
var totalClientID = TotalClientID;
In codebehind:
void GridView1_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.Footer)
{
TotalClientID = ((TextBox)e.Row.FindControl("total")).ClientID;
}
}
<script language="javascript" type="text/javascript">
function Calculate() {
var grid = document.getElementById("<%=grid.ClientID%>");
var sum = 0;
for (var i = 1; i < grid.rows.length; i++) {
var Cell = grid.rows[i].getElementsByTagName("input");
if (!Cell[4].value) {sum += 0; } else { sum += parseFloat(Cell[0].value);}
}
alert(sum);
}
</script>
<asp:TemplateField HeaderText="Current payment" >
<ItemTemplate>
<asp:TextBox ID="txtvalue" runat="server" Width="70px" BorderStyle="None" onkeyup="Calculate();" ></asp:TextBox>
</ItemTemplate>
<ItemStyle Width="120px" />
</asp:TemplateField>`enter code here`