Bootstrap validation with ASP.NET framework 4.5 Web Forms - javascript

I have some ASP.NET aspx form that contains:
<div class="form-group input-group" runat="server" id="div_last_name">
<span class="input-group-addon glyphicon glyphicon-user"></span>
<asp:TextBox ID="TextBox4" CssClass="form-control required" runat="server" placeholder="Last Name"></asp:TextBox>
</div>
<div class="form-group input-group" runat="server" id="div_email" >
<span class="input-group-addon">#</span>
<asp:TextBox ID="TextBox1" CssClass="form-control required" runat="server" placeholder="E-Mail"></asp:TextBox>
</div>
I want to validate using this jQuery, but I don't know how to use it.
jQuery(document).ready(function ($) {
$("#btnRegister_Click").click(function () {
var error = 0;
$('input.required').each(function (i, item) {
if ($(item).val() == '') {
$(item).addClass('form-control has-error');
error = 1;
}
else {
$(item).removeClass('form-control has-error');
}
});
if (error) {
return false;
}
});
var min_height = jQuery(window).height();
jQuery('div.col-lg-6 col-lg-offset-3').css('min-height', min_height);
jQuery('div.col-lg-6 col-lg-offset-3').css('line-height', min_height + 'px');
$(".inner", ".boxed").fadeIn(500);
});

Where it says:
$("#btnRegister_Click")
You need to replace that with the name of your button. If it's a regular HTML button, just use the name of your button like:
$("#nameofbutton")
If you using Server Control, you need to get the unique client id of the button. You can do that using:
$('#<%= nameofbutton.ClientID %>')

Related

Unable to get values from individual check boxes in JavaScript

I am working on an asp.net webforms page. I have three html checkboxes and if any of them are checked I have to append the corresponding values to a JavaScript string. When I execute the btnSave, the saveOrderTypes() is called and goes up to alert("D"); and then exits. I don't see any JavaScript error in the console. I am not sure why this is happening. I tried to get the values using jQuery and similar issue happens.
<asp:Content ID="scriptArea" runat="server" ContentPlaceHolderID="headerScript">
<script>
function saveOrderTypes() {
alert("In saveOrderTypes");
var orderTypes = '';
if (document.getElementById('chkDelivery').checked) {
orderTypes = 'D';
alert("D");
}
if (document.getElementById('chkUPS').checked) {
orderTypes = orderTypes + 'U';
alert("U");
}
if (document.getElementById('chkCustomer').checked) {
orderTypes = orderTypes + 'C';
alert("C");
}
alert("orderTypes: " + orderTypes);
//more code here
}
$(document)
.ready(function () {
});
</script>
</asp:Content>
<asp:Content ID="mainDivision" ContentPlaceHolderID="mainContent" runat="server">
<div class="row" style="width: 100%">
<div class="col-sm-4">
<input type="checkbox" id="chkDelivery">
<label >Delivery</label><br>
<input type="checkbox" id="chkUPS">
<label >UPS</label><br>
<input type="checkbox" id="chkCustomer">
<label >Customer</label><br>
</div>
</div>
<button type="button" id="btnSave" onclick="javascript:saveOrderTypes();return false;"
>Save</button>
</asp:Content>

Compare first letter from 2 textboxes in asp.net forms

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>

asp.net code doesn't call the javascript function

I am working on a project where I have to show and hide buttons based on drop down selection. Please find the attached fiddler link. My function is not getting called/nothing is happening when I select the drop down values. Any help?!
Page code:
<div class="span6 offset2">
<br />
<div class="row">
Location ID
<select id="iloc_Id" runat="server" class="form-control" style="width: 50%" visible="true" onchange="validate()">
<option disabled="">All Locations</option>
<option value ="1">1- Verona</option>
<option value ="2">2- Como</option>
</select>
</div>
</div>
<br/>
<div class="row">
<asp:LinkButton ID="LinkButton1" CssClass="btn btn-success" runat="server" Width="50%"> First Report </asp:LinkButton>
</div>
<br />
<div class="row">
<asp:LinkButton ID="LinkButton2" CssClass="btn btn-success" runat="server" Width="50%" OnClick="Report2"> Second Report
</asp:LinkButton>
</div>
Javascript:
function validate()
{
var selected_loc = $("#iloc_Id").val();
if (selected_loc == '1')
{
$('#LinkButton1').show();
$('#LinkButton2').hide();
}
else if (selected_loc == '2')
{
$('#LinkButton1').hide();
$('#LinkButton2').show();
}
else
{
$('#LinkButton1').show();
$('#LinkButton2').show();
}
link: https://jsfiddle.net/rickfiddle/5pvwznge/5/
Your code is working fine, just need to add a closing bracket at the end
function validate()
{
var selected_loc = $("#iloc_Id").val();
alert(selected_loc);
if (selected_loc == '1')
{
$('#LinkButton1').show();
$('#LinkButton2').hide();
}
else if (selected_loc == '2')
{
$('#LinkButton1').hide();
$('#LinkButton2').show();
}
else if (selected_loc == '3')
{
$('#LinkButton1').hide();
$('#LinkButton2').hide();
}
else
{
$('#LinkButton1').show();
$('#LinkButton2').show();
}
}
and change the jsfiddle configuration Load Type from
On Load
to
No wrap - bottom of <head>
In the javascript code, after closing validate() function add:
document.getElementById("iloc_Id").onchange = function() {validate()};

Textbox should be disabled unless a certain option in the dropdown box is selected

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>

Javascript Validation not working in C# (Error message)

Here is the javascript validation code:
if (document.getElementById("<%=txtCategoryName.ClientID %>").value.trim() == "") {
document.getElementById("<%=dvMessage.ClientID %>").innerHTML = "Please enter Category.";
document.getElementById("<%=txtCategoryName.ClientID %>").focus();
document.getElementById("<%=txtCategoryName.ClientID %>").classList.add("ErrorControl");
// document.getElementById("<%=txtCategoryName.ClientID %>").style.outline = '1px solid red';
// document.getElmentById("<%=txtCategoryName.ClientID %>").style.border = '3px solid red';
return false;
}
if (document.getElementById("<%=txtCategoryDescription.ClientID %>").value.trim() == "") {
document.getElementById("<%=dvMsg.ClientID %>").innerHTML = "Please enter Category Description.";
document.getElementById("<%=txtCategoryDescription.ClientID %>").focus();
document.getElementById("<%=txtCategoryDescription.ClientID %>").classList.add("ErrorControl");
// document.getElementById("<%=txtCategoryDescription.ClientID %>").style.outline = '1px solid red';
return false;
}
}
<script>
function checkfunction(val) {
if (val != "") {
document.getElementById("<%=txtCategoryName.ClientID %>").classList.remove("ErrorControl");
// document.getElementById("<%=dvMessage.ClientID %>").style.display = 'none';
document.getElementById("<%=txtCategoryDescription.ClientID %>").classList.remove("ErrorControl");
// document.getElementById("<%=dvMsg.ClientID %>").style.display = 'none';
}
}
</script>
Here is the text box:
<div class="field">
<div id="dvMessage" runat="server" style="color: Red" >
</div>
<label>
Category Name <em>*</em>
</label>
<div>
<asp:TextBox ID="txtCategoryName" runat="server" CssClass="form-01-control" onkeyup="checkfunction(this.value)" placeholder="Enter Category Name" ></asp:TextBox>
</div>
<div id="dvMsg" runat="server" style="color: Red">
</div>
<label>
Category Description <em>*</em></label>
<div>
<asp:TextBox ID="txtCategoryDescription" runat="server" CssClass="form-01-control" onkeyup="checkfunction(this.value)" placeholder="Enter Category Description"></asp:TextBox>
</div>
<label>
Parent Category </label>
<div>
<asp:DropDownList ID="ddlParentCategory" runat="server" Width="250px" class="form-01-control">
</asp:DropDownList>
</div>
<label>
Category Image</label>
<div>
<asp:FileUpload ID="fuImage" runat="server" />
<asp:Image ID="imgCategory" Width="100" Height="100" runat="server" />
</div>
</div>
The problem is that validation not working properly. The ERROR MESSAGE shows I'm having a problem. Please tell me what to do for multiple textbox and dropdown and how to use javascript validation?
Sir, is something like this what you need? And as Abhay said, there's a load of plugins you can use, jquery is just a javascript library.
<script>
var catName = {
'label' : document.getElementById("<%=dvMessage.ClientID %>"),
'textbox' : document.getElementById("<%=txtCategoryName.ClientID %>")
},
catDesc = {
'label' : document.getElementById("<%=dvMsg.ClientID %>"),
'textbox' : document.getElementById("<%=txtCategoryDescription.ClientID %>")
},
noText = function hasText( textbox ) {
return textbox.value.trim().length === 0;
};
// This entire part might be redundant, unless the textbox comes back from the server with text already inside it.
// If the textbox is always empty at startup, this part could be replaced by placing the text already into the div.
if (noText(catName.textbox)) {
catName.label.innerHTML = "Please enter Category.";
catName.textbox.focus()
catName.textbox.classList.add("ErrorControl");
}
if (noText(catDesc.textbox)) {
catDesc.label.innerHTML = "Please enter Category Description.";
catDesc.textbox.focus()
catDesc.textbox.classList.add("ErrorControl");
}
function checkfunction( textValue ) {
var catNameCls = catName.textbox.classList,
catDescCls = catDesc.textbox.classList;
if (textValue.length !== 0) {
if (catNameCls.contains("ErrorControl")) catNameCls.remove("ErrorControl");
else catNameCls.add("ErrorControl");
if (catDescCls.contains("ErrorControl")) catDescCls.remove("ErrorControl");
else catDescCls.add("ErrorControl");
}
}
</script>

Categories