I have a simple in VB/ASP.NET form containing two text boxes, I am attempting to apply some validation to the first text box using JavaScript. This is the first time I have attempted this and am having some trouble.
I have a label beside the text box stating an error, this labels visibility property is set to False. I wish the labels visibility to turn true if the text box is empty when the user loses focus.
For this I have used the onBlur option within the tags of the text box. It then calls the JavaScript function and should set the label to Visible but it does not. I have tested to see if it is entering the function by using an alert instead and that works. The problem seems to be trying to alter the visibility property of the label.
Here is the portion of my code:
The JavaScript:
function myRegEx(frm) {
if ( boxUsername.value == "" ) {
invalidUser.visible = True;
return false;
}
}
The form:
<asp:TextBox onblur="return myRegEx(this)" id="boxUsername" runat="server" Width="200px"></asp:TextBox>
<asp:Label id="invalidUser" runat="server" visible="False" forecolor="Red" text="* Username must be alphanumeric with no special characters"></asp:Label>
Any help would be brilliant.
Here's another StackOverflow question that has the answer for you:
Change visibility of ASP.NET label with JavaScript
I suggest you use and ASP.Net Validation control, specifically the RequiredFieldValidator.
This will take care of the label for you, plus make certain the correct validation happens both client side (javascript) and server-side (vb).
You're using the deprecated IE-only feature that turns elements with IDs into global variables.
You should call document.getElemenntById instead.
Also, you need to use ASP.Net's generated client IDs.
Finally, to hide an element, you need to use CSS; HTML doesn't have a visible property.
For example:
document.getElementById("<%=invalidUser.ClientID %>").style.display = "none";
However, you should use ASP.Net's built-in validation feature instead.
Why not use an ASP.NET RequiredFieldValidator like so:
<asp:TextBox onblur="return myRegEx(this)" id="boxUsername" runat="server" Width="200px"></asp:TextBox>
<asp:RequiredFieldValidator ControlToValidate="boxUsername" Display="Dynamic" ErrorMessage="Please enter a value" />
If that is too simplistic then you can use a RegularExpressionValidator:
<asp:TextBox onblur="return myRegEx(this)" id="boxUsername" runat="server" Width="200px"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ErrorMessage="Please enter alpha numeric characters." ValidationExpression="[my reg ex]" ControlToValidate="boxUsername" Display="Dynamic" />
Related
I have a user control that is used inside a form. The control contains two standard Asp.Net validation controls.
Here's the code snippet - as you can see there is a required field validator and a regular expression validator:
<asp:Panel ID="pnlInputControl" runat="server" CssClass="input-control">
<div class="input-wrapper input-text half-width">
<asp:TextBox ID="tbInput" runat="server"
CssClass="no-space"
MaxLength="11"
type="tel">
</asp:TextBox>
</div>
<asp:RequiredFieldValidator ID="rfvInput" runat="server"
ControlToValidate="tbInput"
Display="Dynamic"
SetFocusOnError="True"
CssClass="validator">
</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="revInput" runat="server"
ControlToValidate="tbInput"
Display="Dynamic"
SetFocusOnError="True"
CssClass="validator">
</asp:RegularExpressionValidator>
</asp:Panel>
I validate a telephone number - the text box itself also restricts the number of characters to 11 which is the max size of a UK number.
Here's a sample regular expression:
^0[12]\d{8,9}$ - home phone number
I also try to mask the input, removing spaces with a javascript function - triggered by the class labelled "no-space" on the textbox.
$("body").on("input", "input.no-space", removeSpace);
function removeSpace() {
$(this).val(function (_, v) {
return v.replace(/\s+/g, '');
});
}
This works in harmony, on all browsers but MS Edge.
On Edge, it breaks the Asp.Net validation - the validator doesn't kick in - basically it locks the entire form because it is a required field.
The thing is I don't get any errors, so aside from removing the class completely and adding a hint to let the user know not to enter spaces, I'm not sure what else I can do.
Any ideas - either to go about fixing the problem or perhaps a better workaround?
I would allow more characters and use a regex to clean up the field when the focus changes from that specific input field.
How you clean that up with regex would depend on what your expectations are from a user.
If you are confident that users will only be entering UK numbers--you could just replace all non-digit chars.
I do not work in JQ, but this is the vanilla JS
<input id="phone">
document.getElementById("phone").addEventListener("blur", phoneCleanup);
function phoneCleanup() {
var phone = this.value;
this.value = phone.replace(/\D+/g, '');
}
You can simply disallow the "space" key to be pressed in the input type=tel textboxes.
$('input[type=tel]').keydown(function (e) {
return (e.keyCode !== 32);
});
I'm not super familiar with javascript but I'm working on it, I'm trying to do a "same as billing address" type checkbox to fill some textboxes on the same form with data from other textboxes. I found a few solutions online but they weren't working for me. I'm probably overlooking something simple, but I've tried quite a few. Here's what I currently have:
function AutoFillBilling()
{
var text = document.getElementById("CustContact").Value;
alert(text);
}
The alert pops up, but just says undefined, I also tried $("#CustContact").Value to no avail. Below is the textbox I'm trying to access
<asp:Textbox runat="server" ID="CustContact" ClientIDMode="Static" type="text" placeholder="Contact" class="required"/>
What am I missing?
Properties begin with lowercase letters in JavaScript:
var text = document.getElementById("CustContact").value;
Additionally, while the ClientIDMode="Static" certainly should be explicitly setting the client-side id property, when debugging you may want to examine the HTML just to make sure. When using JavaScript, looking only at your server-side markup leaves you unnecessarily blind.
You can use it as such
<asp:CheckBox ID="Postal_Same_As_PermCheckBox" runat="server" onclick="copyPermAddress(this);" />
And JavaScript as
<script type="text/javascript">
function copyPermAddress(e) {
if (e.checked) {
document.getElementById('Postal_Adrs_Line_1TextBox').value = document.getElementById('Perm_Adrs_Line_1TextBox').value;
document.getElementById('Postal_City_VillageTextBox').value = document.getElementById('Perm_City_VillageTextBox').value;
} else {
document.getElementById("Postal_Adrs_Line_1TextBox").removeAttribute('readonly', 'readonly');
document.getElementById("Postal_City_VillageTextBox").removeAttribute('readonly', 'readonly');
}
}
In this example I am assuming that you are using client id mode as static on the controls mentioned in the JavaScript, if it is not then you may use <%# xxxx.ClientID%> blocks to access their IDs
I have this html block at an aspx page:
<td class="NormalBold">
<asp:TextBox runat="server" ID="txtSendSummary" ClientIDMode="Static" CssClass="NormalTextBox" style="width: 170px;" Enabled="False" ></asp:TextBox>
<asp:RegularExpressionValidator ID="txtSendSummaryValidEmail" runat="server" ClientIDMode="Static" ControlToValidate="txtSendSummary" ErrorMessage="*" ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*"/>
</td>
I tried to reset the "*" with :
document.getElementById('txtSendSummaryValidEmail').value = "";
But still "*" is there!
How i can reset this span of the validator?
Thanks in advance!
You have two problems here. Firstly span elements do not have a value, so you'll need to change that to use innerText instead:
document.getElementById('txtSendSummaryValidEmail').innerText = "";
The second problem you may face is that ASP.NET ensures that id attributes on elements like these are unique by prefixing them. Where you're declaring your ID as txtSendSummaryValidEmail, the final result is going to look something like c001_c001_txtSendSummaryValidEmail.
Depending on which browsers you need to support, your best bet may be to use CSS's substring-matching attribute selector to match the end of the ID within a querySelector method:
document.querySelector('[id$="txtSendSummaryValidEmail"]').innerText = "";
Basically I am creating a simple function in javascript to check if a textbox value has changed from what it was originally and if so to warn the user the impact the change will have. If the user clicks yes, do nothing, if they click no then I want to set the value of the textbox back to the original value it should be for them.
EDIT
Okay it seems I was mistaken as to the root of the problem. It seems that the inpUsername which is a hidden input I have is blank from the beginning. How do I set it correctly in the asp portion of the code so it takes the value of another textbox on the same control?
I currently have:
<input type="hidden" id="inpUsername" runat="server" value=
%#DataBinder.Eval(Container.DataItem,"txtUsername")%> />
This returns the error: BC30456: 'DataItem' is not a member of 'System.Web.UI.Control'. However if I add additional quotes around the value it outputs "/> to the screen
The txtUsername declaration as requested is:
<asp:TextBox ID="txtUsername" runat="server" CssClass="Textbox" Style="width:100%"
onchange="checkForUsernameChange()"/>
var txtUsername = document.getElementById(" <%=txtUsername.ClientID%>").value;
There's some spaces before the ID. I'm pretty sure you wanted :
var txtUsername = document.getElementById("<%=txtUsername.ClientID%>").value;
Or maybe the spaces were intended, in which case the confirm should also include those spaces.
In my form, there are password field, so that I cannot use postback.
I need to validate everything in client side.
But the ValueToCompare may change by the user input.
How to change the ValueToCompare in CompareValidator by javascript?
Thanks.
Maybe I need to tell the full case.
I have two input, said a & b, the sum of this two number cannot greater than c.
For example,
c is 90
a is inputted 30, then b cannot be greater than 60.
if b is then entered to 40, than a cannot be greater than 50.
I am now doing this in server side, how can I do it in client side by using asp.net validations?
This works for me:
<asp:CompareValidator ID="valOptionsCmp" runat="server"
ErrorMessage="!!!"
ControlToValidate="tbPrixOptions" Display="Dynamic"
ValueToCompare="1"
Operator="GreaterThanEqual"
Type="Integer"/>
//in javascript
<%=valOptionsCmp.ClientID%>.valuetocompare = yourvalue
From:
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.comparevalidator.aspx
Compares the value entered by the user in an input control with the value entered in another input control, or with a constant value.
Those are your choices. Compare two controls, or compare one against a constant.
If neither suits, you may need to roll your own.
If you means something like Enter Your Password and Please Reenter Password type of comparison then you don't need to use ValueToCompare. Instead you use ControlToCompare and ControlToValidate like this:
<asp:TextBox id="password" runat="server" TextMode="password"/>
<asp:RequiredFieldValidator id="rfvPass" runat="server"
ControlToValidate="password" Text="*"/>
<asp:textbox id=="rePassword" runat="server" TextMode="Password"/>
<asp:CompareValidator id="cmpPass" runat="server" ControlToCompare="password"
ControlToValidate="rePassword" Type="String" Operator="Equal"/>
I solved the same problems with firebug helps:
<script type="text/javascript">
$(document).ready(function() {
$("select[id$=ddlYears]").change(function() {
var year= $(this).val();
<%= cvDataMinApertura.ClientID%>.valuetocompare = "01/01/"+year;
});
});
</script>
I use JQuery for change compare validator cvDataMinApertura on change of years drop down list.