I want custom validator dynamic messages. Custom validator for required field and regular expression. I don't want to use required field validator and regular expression validator it creates more problems for me.
Here is javascript code
<script type="text/javascript">
function CheckMyText(sender, args) {
var compare = RegExp("^.{1,10}$");
args.IsValid = compare.test(args.Value)
return;
}
</script>
Here is custom validator and text field code
<asp:TextBox ID="summary" runat="server" Width="627px" CssClass="texrbox"></asp:TextBox>
<asp:CustomValidator ID="CustomValidator2" runat="server" ClientValidationFunction="CheckMyText" ControlToValidate="summary" ErrorMessage="" Text="*" ValidateEmptyText="true"></asp:CustomValidator>
It is working fine but I want to show message when regular expression error fired Only 10 characters allowed and for required field I want to show Required Field. How to do it. I want to show bith messages in validation summary.
A validator renders as a <span> element in html. So you can use that to change your error message.
document.getElementById('<%= CustomValidator2.ClientID %>').innerHTML = "My custom error msg";
Or change the ErrorMessage:
<%= CustomValidator2.ClientID %>.errormessage = "Error for summary";
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 want to distinguish between required field validators and regular expression validators in my Javascript code so I can change the background color of my controls depending on the validator. Any idea how can I do it?
EDIT :
this is the script that i want to modify ( add a condition depending on required validators or regular expression validators)
If you are using client-side jQuery validation, which is the default in new ASP.NET MVC and Webforms projects, then you already have the attributes you need in HTML.
For example take a look at the following code in ASP.NET Webforms:
<div class="col-md-10">
<asp:TextBox runat="server" ID="TextBox1" CssClass="form-control" TextMode="Email" />
<asp:RequiredFieldValidator runat="server" ControlToValidate="Email"
CssClass="text-danger" ErrorMessage="The email field is required." />
<asp:RegularExpressionValidator runat="server" ControlToValidate="Email"
CssClass="text-danger" ErrorMessage="The email is not valid" />
</div>
This code produces a textbox input field and two sibling span HTML elements for the validators with corresponding data attributes that identify the validator type, the validation function to execute etc.
So the output for the required validator is:
<span data-val-evaluationfunction="RequiredFieldValidatorEvaluateIsValid" data-val-initialvalue="" data-val="true" data-val-errormessage="The email field is required." data-val-controltovalidate="MainContent_Email"></span>
and for a regex validator it is:
<span data-val-evaluationfunction="RegularExpressionValidatorEvaluateIsValid" data-val="true" data-val-errormessage="The email field is required." data-val-controltovalidate="MainContent_Email"></span>
I have omitted some of output details for simplicity.
So you can just use the existing data attributes that ASP.NET outputs and interpret them in your javascript code.
In fact the Page_Validators array contains that data already. So you can do something like this:
switch(Page_Validators[i].evaluationfunction.name){
case "RequiredFieldValidatorEvaluateIsValid":
// do stuff for required field validators
break;
case "CustomValidatorEvaluateIsValid":
// do stuff for custom validators
break;
case "RegularExpressionValidatorEvaluateIsValid":
// do stuff for regex validators
break;
case "CompareValidatorEvaluateIsValid":
// do stuff for compare validators
break;
}
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" />
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.