I need to do the validation for the P.O box on text changed event. If the user types P.O Box in the address text box and also request for expedite shipping by checking a chec box then I need to show the warning message to the user saying that expedite shipping cannot be done to the P.O box address. For this, I have the following code on my aspx page:
<asp:TextBox ID="txtAddress" runat="server" style="text-transform:uppercase;" onChange="addchange();" ></asp:TextBox>
<asp:CheckBox ID="chkExpShipping" Font-Bold="true" ForeColor="Red" CssClass="test" Text="ExpediteShipping" runat="server" />
<asp:Panel ID="pnlMessage" runat="server" Visible="false" >
<div class="ui-radio ui-btn" style="font-size:20px;">
<span style="color:blue"><b> Warning: Express delivery cannot be done to the P.O Box address</b> </span>
</div>
</asp:Panel>
if the user types P.O box address in the txtAddress and also checks the chkExpShipping check box then I want the pnlMessage to be visible and show the warning message. If the user changes the txtAddress content from P.O box to regular address then I want the warning to be hidden. In order to achieve this, I wrote this code:
<script type="text/javascript">
function addchange() {
debugger;
var add = document.getElementById('txtAddress').value;
var postalRGEX = /^?i)\b(?:p(?:ost)?\.?\s*(?:[o0](?:ffice)?)?\.?\s*b(?:[o0]x)?|b[o0]x;
var PostalResult = postalRGEX.test(add);
if (PostalResult == true) {
document.getElementByID('<%=pnlMessage.ClientID%>').style.display = "block";
}
else {
document.getElementByID('<%=pnlMessage.ClientID%>').style.display = "none";
}
}
</script>
when I start typing in the txtAddress text box, no validation happens. The code does not even go the addChjange javascript function.
any help with this will be appreciated.
Part of the problem may be that you're doing a comparison with == when JavaScript has much more predictable results when using the triple ===.
Try:
if (PostalResult === true)
Related
I have an asp.net website. I want to manipulate a webpage based on return value of a confirmation popup.
I have a drop down with some values. "cancel" is one of those values. So when user selects this item, a confirmation box asking user "Are you sure you want to cancel the ticket"? is displayed.
Here is my code,
HTML:
<asp:DropDownList ID="ddlStatus" runat="server" CssClass="selectstyle" DataTextField="Name" DataValueField="ID" onchange ="GetSelectedItem(this);" />
<asp:Panel ID="pnl_Cancel" runat="server" Visible="false">
<tr>
<td class="label" align="right">
Cancellation Reason :
</td>
<td>
<asp:TextBox ID="tbxCancellationReason" runat="server" CssClass="selectstyle" TextMode="MultiLine" Width="400" Height="50"></asp:TextBox>
</td>
</tr>
</asp:Panel>
JavaScript :
<script type="text/javascript">
function GetSelectedItem(x) {
if (x.value == 4) {
if (confirm("Are you sure you want to cancel support ticket ?") == true) {
alert("Yes");
document.getElementById("pnl_Cancel").style.visibility = 'visible';
}
}
}
</script>
which is displaying a popup as I want.
Now, I want to make a panel visible if user clicked on "OK" and reset dropdownlist if user clicked on "Cancel". I am getting "Yes" alert message but the panel visibility is not working.
First, you need to do a below things in code-behind file.
Register client IDs of pnl_cancel and ddlStatus controls. You will need these client IDs of the controls to access them in JavaScript
Add style attribute to pnl_cancel with value display:none. This is to ensure that the control is rendered in HTML but is hidden
This link here simulates the final rendered HTML. It will help resolve your problem.
function GetSelectedItem(x) {
if (x.value == 4) {
if (confirm("Are you sure you want to cancel support ticket ?")) {
document.getElementById("pnl_Cancel").style.display = 'block';
} else {
x.value = "";
}
}
}
I'm working on a legacy .NET WebForms project where the front-end is being updated with Bootstrap.
There are some .NET Validation Controls which are validating on the ClientSide, but the "has-error" class needs to be added to the parent div of the input fields to match the Bootstrap markup.
Is there an event hook or a way of extending the .NET Validators so that I can add the "has-error" class to an invalid control group and remove it when valid?
e.g: Here is my markup which works server side:
<div class="form-group <%= IIf(RequiredFieldValidator1.IsValid, "has-error", "") %>">
<label class="control-label">Test</label>
<asp:TextBox runat="server" ID="TextBox1" CssClass="form-control" />
<asp:RequiredFieldValidator runat="server" ID="RequiredFieldValidator1"
ContolToValidate="TextBox1" ErrorMessage="TextBox1 is Required!" />
</div>
I was requiring the has-feedback class on the form-group div as well as the glyphicon tick and crosses depending on whether the input was valid or not. What I have found that works in my solution is to override asp.net's client side function ValidatorUpdateDisplay (note my code utilizes jQuery although you could use native JavaScript):
var originalValidatorUpdateDisplayMethod;
if (typeof(ValidatorUpdateDisplay) == "function"
&& typeof(originalValidatorUpdateDisplayMethod) != "function") {
originalValidatorUpdateDisplayMethod = ValidatorUpdateDisplay;
// now overwrite original method
ValidatorUpdateDisplay = function (val) {
originalValidatorUpdateDisplayMethod(val); // call original method first
var parent = $("#" + val.controltovalidate).parent();
if (parent.hasClass("form-group")) {
parent.addClass("has-feedback");
parent.toggleClass("has-success", val.isvalid);
parent.toggleClass("has-error", !val.isvalid);
var glyph = parent.find("span.form-control-feedback");
if (glyph.length == 0) {
glyph = $("<span class='glyphicon form-control-feedback' />");
parent.append(glyph);
}
glyph.toggleClass("glyphicon-ok", val.isvalid);
glyph.toggleClass("glyphicon-remove", !val.isvalid);
}
}
}
This adds the bootstrap validation to fields when they change as well as when an event on a control that has causesvalidation="true" is triggered.
Note: this is only adding the validations on the client side.
You'll need to put a id on the element
<div id="div1" class="someclass">
<img ... id="image1" name="image1" />
</div>
and this is the javascript which adds a class to a <div> element
var d = document.getElementById("div1");
d.className = d.className + " otherclass";
Here is what I did:
<asp:Panel ID="pnlNumberOnly" runat="server" CssClass="form-group">
<label for="<%= tbNumberOnly.ClientID %>" class="control-label">Enter a number:</label>
<asp:TextBox ID="tbNumberOnly" runat="server" CssClass="form-control" />
<asp:RegularExpressionValidator runat="server" ID="regExpNumberOnly"
ControlToValidate="tbNumberOnly"
Display="Dynamic"
ErrorMessage="Numbers only" CssClass="control-label"
ValidationExpression="^\d+$" EnableClientScript="True"/>
</asp:Panel>
and then my js looked like this:
$(document).ready(function() {
$('#<%= tbNumberOnly.ClientID %>').change(function() {
if ($('#<%= regExpNumberOnly.ClientID %>').is(':visible')) {
$('#<%= pnlNumberOnly.ClientID %>').addClass('has-error');
} else {
$('#<%= pnlNumberOnly.ClientID %>').removeClass('has-error');
}
});
});
I am using the ASP.NET PasswordRecovery method, and have a couple of CSS buttons to submit the form OR cancel the request.
I also grab the users email address to pass along to the successtext value of PasswordRecovery method, set the ASP hiddenvalue to success, and then try to use javascript to disable the buttons based on this value.
The problem is that this hiddenfield value seems to be set to "success" on initial page load, even though when viewing the source of the rendered page shows NO value.
There is probably a better approach to this, but I have tried several different ways, and this is successful up the point that I cant change the view state of the buttons.
<script runat="server">
protected void resetuserpassword_SendingMail(object sender, MailMessageEventArgs e)
{
e.Message.IsBodyHtml = true;
e.Message.Subject = "Password Assistance";
TextBox txtUserName = (TextBox)resetuserpassword.UserNameTemplateContainer.FindControl("UserName");
string UserEmailID = Membership.GetUser(txtUserName.Text.Trim()).Email;
resetuserpassword.SuccessText = "Password sent to ";
resetuserpassword.SuccessText += UserEmailID;
ValueHiddenField.Value = "Success";
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolderArea" Runat="Server">
<script type="text/javascript">
window.onload = disableButtons;
function disableButtons() {
var element = document.getElementById('ContentPlaceHolderArea_ValueHiddenField');
if (typeof(element) != 'undefined' && element != null) {
if (document.getElementById('ContentPlaceHolderArea_ValueHiddenField').value = 'Success') {
var submitBtnElement = document.querySelector("#submitBtn");
var cancelBtnElement = document.querySelector("#cancelBtn");
submitBtnElement.style.display = "none";
cancelBtnElement.style.display = "none";
}
}
}
function clickSubmit() {
document.getElementById("ContentPlaceHolderArea_resetuserpassword_UserNameContainerID_SubmitButton").click();
}
function clickCancel() {
window.location.replace("~/Login.aspx");
}
</script>
<asp:hiddenfield id="ValueHiddenField" value="" runat="server"/>
<asp:hiddenfield id="ValueHiddenField" value="" runat="server"/>
<asp:PasswordRecovery ID="resetuserpassword" runat="server"
MailDefinition-BodyFileName="~/ResetPasswordEmailTemplate.html"
OnSendingMail="resetuserpassword_SendingMail"
successtext="Password sent to email address on record."
Width="300px" Font-Names="Arial" Font-Size="Small" UserNameTitleText="" >
<InstructionTextStyle Font-Names="Arial" Font-Size="Small" />
<MailDefinition BodyFileName="~/ResetPasswordEmailTemplate.html"></MailDefinition>
<UserNameTemplate>
<div><asp:Label ID="UserNameLabel" runat="server" AssociatedControlID="UserName" style="display:none;"></asp:Label></div>
<div style="font: arial, verdana, sans-serif;font-size: 13px;padding-bottom: 5px;font-weight: bold;">Please Enter your Username</div>
<div><asp:TextBox ID="UserName" runat="server" style="width: 180px;"></asp:TextBox></div>
<div><asp:RequiredFieldValidator ID="UserNameRequired" runat="server" ControlToValidate="UserName" ErrorMessage="User Name is required." ToolTip="User Name is required." ValidationGroup="PasswordRecovery1">*</asp:RequiredFieldValidator></div>
<div><asp:Literal ID="FailureText" runat="server" EnableViewState="False"></asp:Literal></div>
<div style="display: inline;" ><asp:Button ID="SubmitButton" runat="server" CommandName="Submit" Text="Submit" ValidationGroup="PasswordRecovery1" style="display: none;" /></div>
</UserNameTemplate>
</asp:PasswordRecovery>
<div>
<div id="submitBtn" onclick="clickSubmit()">Submit</div>
<div id="cancelBtn" onclick="clickCancel()">Cancel</div>
</div>
</asp:Content>
Your javascript if statement is assigning the value 'Success' to the Hidden Field (single equals sign).
if (document.getElementById('ContentPlaceHolderArea_ValueHiddenField').value = 'Success') {
...
}
Change it to this (double equals sign):
if (document.getElementById('ContentPlaceHolderArea_ValueHiddenField').value == 'Success') {
...
}
I have a textbox whose textmode is set to multiline. Doing this renders the textbox as a textarea. Something to this effect:
<asp:TextBox ID="txtFinBillingTerms" maxlength="500" runat="server" ToolTip="(e.g. 90/10, 30/30/30/10, etc.)" TextMode="MultiLine" Columns="5" Rows="5" Width="300px"></asp:TextBox>
The issue I am having is when I run my project and inspect the textarea the rendered html does not show the maxlength attribute, its as if its gone:
rendered html:
<textarea name="ctl00$MainContent$txtFinBillingTerms" rows="5" cols="5" id="MainContent_txtFinBillingTerms" title="(e.g. 90/10, 30/30/30/10, etc.)" style="width:300px;"></textarea>
This causes issues for me because I am trying to put in some javascript/jquery to limit input of my textarea, namely this:
$('textarea').keypress(function (e) {
var maxLength = $(this).attr('maxlength');
alert(maxLength);
if (e.which < 0x20) {
// e.which < 0x20, then it's not a printable character
// e.which === 0 - Not a character
return; // Do nothing
}
if (this.value.length == max) {
e.preventDefault();
} else if (this.value.length > max) {
// Maximum exceeded
this.value = this.value.substring(0, max);
}
});
But maxLength is always undefined....
MaxLength property isn't applicable for <textarea> so it's simply ignored. From MSDN:
This property is applicable only when the TextMode property is set to TextBoxMode.SingleLine or TextBoxMode.Password.
Lowercase maxlength attribute works on <textarea> but not all browsers supports it so it may depends on that or how ASP.NET will handle that property (it doesn't support it so it may simply remove that attribute).
Edit: You can workaround this limitation using some JavaScript or a validation control with this expression: ValidationExpression="^[\s\S]{0,500}$" (code from here). If you want to perform only client-side validation then you have at least these options:
1) Use a different name for that attribute (like data-maxlength) both in your ASP.NET page and in your JavaScript:
<asp:TextBox runat="server" ID="txtFinBillingTerms"
data-maxlength="500"
ToolTip="(e.g. 90/10, 30/30/30/10, etc.)"
TextMode="MultiLine"
Columns="5" Rows="5" Width="300px">
</asp:TextBox>
With:
var maxLength = $(this).data('maxlength');
2) If you don't use directly your <asp:Input> control in your ASP.NET code then you may use a <textarea runat="server"> instead of official ASP.NET control, like this example:
<textarea runat="server" ID="txtFinBillingTerms"
maxlength="500"
title="(e.g. 90/10, 30/30/30/10, etc.)"
cols="5" rows="5" style="width: 300px">
</textarea>
I am using twitter bootstrap validation class to get success and error in a text-box. I have two text boxes so when a user clicks on any text-box jquery should first check if the text-box is empty if its empty then red colour should appear around the box. When a user start entering data the text-box should change the colour to green. I would like to apply this technique across all the text-boxes. This is what I have done but when running a page it is not working?:
<div class="test">
<div class="form-group has-success">
</div>
</div>
<div class="form-group has-error">
</div>
<div id="pt" class="tab-pane active">
<asp:Label ID="label1" CssClass="form-group" runat="server" Text="Name:"></asp:Label>
<asp:TextBox ID="TextBox1" CssClass="form-control" runat="server" ></asp:TextBox>
<asp:Label ID="label2" CssClass="form-group" runat="server" Text="Surname:"></asp:Label>
<asp:TextBox ID="TextBox2" CssClass="form-control" runat="server"></asp:TextBox>
</div>
Jquery
$("TextBox").click(function () {
if ($.trim($('TextBox').val()) == "") {
$('.form-group has-error');
}
else if ($.trim($('TextBox').val()) != "") {
$('.form-group has-success');
}
});
This is the website i have used to get validation status: bootstrap example which i am following click here under form -> control status
try this:
$(function(){
$("#TextBox1").on("click", function(){
if($("#TextBox1").val().length === 0){
$("#TextBox1").parent().addClass("has-error");
}
});
$("#TextBox1").on("keydown", function(){
if($("#TextBox1").parent().hasClass("has-error")){
$("#TextBox1").parent().removeClass("has-error");
$("#TextBox1").parent().addClass("has-success");
}
});
$("#TextBox2").on("click", function(){
if($("#TextBox2").val().length === 0){
$("#TextBox2").parent().addClass("has-error");
}
});
$("#TextBox2").on("keydown", function(){
if($("#TextBox2").parent().hasClass("has-error")){
$("#TextBox2").parent().removeClass("has-error");
$("#TextBox2").parent().addClass("has-success");
}
});
});
Your HTML seems to be malformed.
I am not sure I understood correctly your question, but if you want to display the divs, then your code should work like that:
$("#tbDepartment").click(function () {
if ($.trim($('#tbDepartment').val()) == "") {
$('.form-group has-error').show();
}
else if ($.trim($('#tbDepartment').val()) != "") {
$('.form-group has-success').show();
}
});