Asp.Net Validation control conflicts with javascript function in MS Edge only - javascript

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);
});

Related

RegularExpressionValidator in asp.net not working for 1 or 2 digit number

I've read other answers to other questions about RegularExpressionValidator but they haven't helped. I'm working on an ASP.NET C# app and I have a text field that needs to be a 1 or 2 digit number. Here's the control:
<asp:TextBox
ID="Hunt_Daily_Sitting_hrs"
runat="server"
class="form-control"
placeholder="hours"
type="number"></asp:TextBox>
As written, even though it specifies type="number", it allows mathematical operators. So people have been entering "6-8" as in "6 to 8 hours". On this page, the regular expression ^\d{1,2}$ flags such an entry. However, in my app, the line
<asp:RegularExpressionValidator
ID="HuntSitRegexp"
Display="Dynamic"
ControlToValidate="Hunt_Daily_Sitting_hrs"
ValidationExpression="^\d{1,2}$"
runat="server"
ErrorMessage="Please enter a number from 1-24"
Font-Size="Large"
ForeColor="Red" />
does not. A 3-digit number is immediately flagged, but an entry such as "6-8" is NOT immediately flagged. However, an entry such as "6-8" DOES fail submission in that the "Submit" button does nothing, indicating that Javascript validation has failed. So the user is left thinking, "What's wrong with the form? It won't submit but there is no error message."
The ValidationExpression="^\d{1,2}$" is fine, but the regex checking is not enabled for an input of number type.
So, you need to change the asp:TextBox control type="number" to type="text".
Try this Reg Ex instead
^[0-9]{1,2}$
I think the answer with changing the type is correct one.
However, I noticed that your
ValidationExpression="^\d{1,2}$"
and
ErrorMessage="Please enter a number from 1-24"
do not match. It will take any 1-2 digit number.
The RegEx expression which will match only numbers 1-24 is following: ^(\d)$|^(1\d)$|^(2[0-4])$

Custom validator dynamic message

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";

ASP.NET webforms - Modifying control CSS depending on validator type in Javascript

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;
}

Editing a labels text value through JavaScript

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" />

How to change the ValueToCompare in CompareValidator by javascript?

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.

Categories

Resources