I have a custom validator for checking if date enetred is valid. but it is always true that makes it not firing. I used to have a comaprevalidator and daterange but it won't work coz as page refreshes, it validates the date of birth and says invalid when it is. So I changed it to customvalidator hoping I will find luck.
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Please enter MM/DD/YYYY format. Invalid Date 01/01/1901 to 12/31/9999"
ControlToValidate="txtAccusedDOB" SetFocusOnError="True" ClientValidationFunction="ServerValidation1" Display="Static">
<asp:Image ID="Image125" runat="server" ImageUrl="~/images/validatearrow.png" />
</asp:CustomValidator>
<ajaxToolkit:ValidatorCalloutExtender
runat="Server" ID="ValidatorCalloutExtender5" TargetControlID="CustomValidator1" Width="250px" HighlightCssClass="highlight"
CssClass="CustomCalloutStyle" PopupPosition="Right" WarningIconImageUrl="~/images/001_11.png"
CloseImageUrl="~/images/001_05.png" />
<asp:TextBox ID="txtAccusedDOB" runat="server" Style="text-transform: uppercase" onkeydown="TrapEnterKey()"
Width="70px" TabIndex="85">
</asp:TextBox>
here's the java script. it always shows the alert("test" + arguments.Value.toString()); The try catch is not working.
function ServerValidation1(source, arguments)
{
try{
var x= new Date();
x = Date.parse(arguments.Value.toString())
arguments.IsValid = true;
alert("test" + arguments.Value.toString());
}
catch(Error r)
{
arguments.IsValid = false;
alert("test OUt" + r.toString());
}
is there a simpler way to check if date entered is valid. I have been struggling on this for days already. thanks.
Related
I want to output a message in case if an invalid date was supplied.
<asp:TextBox ID="RegistrationFromTextBox2" runat="server"></asp:TextBox>
<asp:CustomValidator ID="CustomValidator1" ControlToValidate="RegistrationFromTextBox2" OnServerValidate="CustomValidator1_ServerValidate" ValidationGroup="NewMailingItem" runat="server" ErrorMessage="The date is invalid"></asp:CustomValidator>
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
try
{
DateTime temp;
if (DateTime.TryParse(args.Value, out temp))
{
args.IsValid =true;
}
else
{
args.IsValid = false;
}
}
catch (Exception ex)
{
args.IsValid = false;
}
}
I expect the output message to be located near the field.
Instead I get no response, even though the function works. I only get the error message if I put a validation summary to my form.
Is there away display the message without the validation summary?
Is there away display the message without the validation summary?
You will need to use Text attribute instead of ErrorMessage.
<asp:CustomValidator ID="CustomValidator1"
ControlToValidate="RegistrationFromTextBox2"
OnServerValidate="CustomValidator1_ServerValidate"
ValidationGroup="NewMailingItem"
runat="server"
Text="The date is invalid">
</asp:CustomValidator>
FYI: If you just want to validate date, you could use CompareValidator or Ajax Control Toolkit's Calendar control.
<asp:TextBox ID="RegistrationFromTextBox2" runat="server"
placeholder="MM/DD/YYYY">
</asp:TextBox>
<asp:CompareValidator
ID="RegistrationFromCompareValidator" runat="server"
Type="Date"
Operator="DataTypeCheck"
ControlToValidate="RegistrationFromTextBox2"
Text="The date is invalid">
</asp:CompareValidator>
I have the following code in my ASP.Net (4.0) page, in which there are 2 buttons - 'Button1' and 'Button2', a textbox, a required field validator and a custom validator.
I would like the custom validator to fire only when 'Button1' clicked and not when 'Button2' is clicked and Button2 still needs to evaluate a required field validator. How would I make this happen?
Input 1:
<asp:TextBox id="txtCustomData" runat="server" />
<asp:CustomValidator id="CustomValidator1"
runat="server" ErrorMessage="Number not divisible by 2!"
ControlToValidate="txtCustomData"
ClientValidationFunction="CheckEven" />
<br/>
Input 2:
<asp:TextBox id="TextBox2" runat="server" />
<asp:RequiredFieldValidator ID="rfv1" runat="server" ControlToValidate="TextBox2"
ErrorMessage="* Required" ForeColor="Red" >
</asp:RequiredFieldValidator>
<br/>
<br/>
<asp:Button id="btn1" runat="server" Text="Button1" />
<br/>
<asp:Button id="btn2" runat="server" Text="Button2" />
<script language="javascript">
<!--
function CheckEven(source, args) {
var val = parseInt(args.Value, 10);
if (isNaN(val)) {
args.IsValid = false;
}
else {
args.IsValid = ((val % 2) == 0);
}
}
// -->
</script>
UPDATE 1:
While Rick's answer is a possible answer, I found another approach to handling this situation.
I can use Validation groups when both buttons need to validate 2 different validators and one of the validators is a custom validator. Set ValidationGroup="Group1" for Button1 that needs to evaluate the custom validator and ValidationGroup="Group2" for Button2 that needs to evaluate the required field validator, and include the same values for corresponding validators. There is no need to include ValidationGroup for the textboxes.
Input 1:
<asp:TextBox id="txtCustomData" runat="server" />
<asp:CustomValidator id="CustomValidator1"
runat="server" ErrorMessage="Number not divisible by 2!"
ControlToValidate="txtCustomData"
ClientValidationFunction="CheckEven" />
<br/>
Input 2:
<asp:TextBox id="TextBox2" runat="server" />
<asp:RequiredFieldValidator ID="rfv1" runat="server" ControlToValidate="TextBox2"
ErrorMessage="* Required" ForeColor="Red" ValidationGroup="Group2">
</asp:RequiredFieldValidator>
<br/>
<br/>
<asp:Button id="btn1" runat="server" Text="Button1" ValidationGroup="Group1"/>
<br/>
<asp:Button id="btn2" runat="server" Text="Button2" ValidationGroup="Group2"/>
<script language="javascript">
<!--
function CheckEven(source, args) {
var val = parseInt(args.Value, 10);
if (isNaN(val)) {
args.IsValid = false;
}
else {
args.IsValid = ((val % 2) == 0);
}
}
// -->
</script>
UPDATE 2:
If you end up using custom javascript in OnClientClick event of the button, then you need to be careful with your javascript else you might end up having your button never postback even when data is valid.
For example if you have written a custom javascript function called 'ValidateData( )' then first make sure that it always has return true or return false statement in it, and second your OnClientClick should use this function in the manner shown below. Most developers will simply use OnClientClick = "return ValidateData();" which will make the ASP.Net button to NEVER perform an ASP.Net post back even when the data is evaluated as valid, since the default __doPostBack JavaScript function in ASP.Net will never get called (assuming UseSubmitBehavior="false" for this button, if UseSubmitBehavior="true" then __doPostBack is not used and button will postback).
<asp:Button id="btn1" runat="server" Text ="Button1"
OnClientClick="var r = ValidateData(); if (!r) { return false; } " />
<script type=<script type="text/javascript">
function ValidateData( )
{
var x = document.getElementById('xy1');
if(x.value == '1')
{
return false;
}
return true;
}
</script>
Include the CausesValidation attribute and set it to False. Your button will not trigger validation.
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.causesvalidation(v=vs.110).aspx
<asp:Button id="btn2" runat="server" Text="Button2" CausesValidation="False"/>
I'm obviously new to ASP.Net, but I have a quick question.
I have text boxes and labels for forms on the main page. One of the text boxes is a wager amount. But since the input is a text box, I keep getting errors when trying to pass one of the other text box ID's (stake) to the RangeValidator.
To clear that up.. I need the RangeValidator for wager to be between 1 and stake. Since obviously a wager can't be more than the stake.
I tried using CInt(currentstake.Text) and some other things, but it seems like it's stuck as a string/text type.
Here's an example of what I've been trying to do:
<asp:RangeValidator ID="RangeValidator2" ControlToValidate="wager" ForeColor="Red" ErrorMessage="Please enter a valid wager." MinimumValue="1" MaximumValue="CInt(currentstake.Text)" Type="Integer" runat="server"></asp:RangeValidator>
Any easy way to fix this? Thanks!
I would use a CustomValidator which is the most flexible validator type. Here's a complete sample with a client- and servervalidation function incl. validation-groups:
aspx:
<asp:TextBox ID="Wager" runat="server" ValidationGroup="WagerVG"></asp:TextBox>
<asp:TextBox ID="Stake" runat="server" ValidationGroup="WagerVG"></asp:TextBox>
<asp:CustomValidator ValidationGroup="WagerVG" ID="CustomValidator1" runat="server"
OnServerValidate="WagerValidation"
ClientValidationFunction="WagerValidation_CV"
ValidateEmptyText="true"
ErrorMessage="Please enter a valid wager."
ForeColor="Red">
</asp:CustomValidator>
<asp:Button ID="SubmitWager" Text="Submit" ValidationGroup="WagerVG" runat="server" />
javascript validation:
<script type="text/javascript">
function WagerValidation_CV(sender, e) {
var valid = false;
var txtWager = document.getElementById('<%= Wager.ClientID %>');
var txtStake = document.getElementById('<%= Stake.ClientID %>');
if (txtWager != null && txtStake != null) {
var wager = parseInt(txtWager.value);
var stake = parseInt(txtStake.value);
valid = wager >= 1 && wager <= stake;
}
e.IsValid = valid;
}
</script>
servervalidation-function:
protected void WagerValidation(object source, ServerValidateEventArgs args)
{
bool valid = true;
int wager, stake;
if (!int.TryParse(Wager.Text, out wager))
valid = false;
if (!int.TryParse(Stake.Text, out stake))
valid = false;
valid = valid && wager >= 1 && wager <= stake;
args.IsValid = valid;
}
A CustomValidator is typically used if multiple controls are dependent of each other. Remember to set ValidateEmptyText="true" to force validation even with empty textboxes and to omit the ControlToValidate to force validation on both controls.
Edit: another option is to use a combination of two CompareValidators and two RequiredFieldValidators(if you want to prevent empty texts):
<asp:CompareValidator ID="CompareValidator1" runat="server" ForeColor="Red" ValidationGroup="WagerVG"
ControlToValidate="Wager" ControlToCompare="Stake"
Operator="LessThanEqual" Type="Integer"
ErrorMessage="Please enter a value greater 0 and less or equal stake">
</asp:CompareValidator>
<asp:CompareValidator ID="CompareValidator2" runat="server" ForeColor="Red" ValidationGroup="WagerVG"
ControlToValidate="Wager" ValueToCompare="1"
Operator="GreaterThanEqual" Type="Integer"
ErrorMessage="Please enter a value greater 0 and less or equal stake">
</asp:CompareValidator>
One way to achieve this is using CustomValidation you can create a custom function javascript or in the server that check if the value is correct, so you can see this article for more information
Other option si to use an CompareValidator but doesn't work for range, you could also validate that the value is less than currentstake. So:
<asp:CompareValidator ID="CompareValidator1"
runat="server"
ControlToCompare="currentstake"
ControlToValidate="wager"
Operator="LessThan"
ErrorMessage="Wrong Value"
SetFocusOnError="True">
I am using asp.net validation controls for validating user input. What i want is to change the label text with the error message generated by the validation control.
<asp:Label ID="Label1" runat="server" Text="Whats your name"></asp:Label>
<asp:TextBox ID="nameB" Width="322px" Height="30px" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" ValidationGroup="business" runat="server" ErrorMessage="Please tell us your name." ControlToValidate="nameBuisness" CssClass="errMsg" Display="Dynamic"></asp:RequiredFieldValidator>
Thank you.
One way is to handle the submit-button's OnClientClick-event and call a javascript function like:
<script type="text/javascript">
function displayValidationResult() {
// Do nothing if client validation is not available
if (typeof (Page_Validators) == "undefined") return;
var LblName = document.getElementById('LblName');
var RequiredName = document.getElementById('RequiredName');
ValidatorValidate(RequiredName);
if (!RequiredName.isvalid) {
LblName.innerText = RequiredName.errormessage;
}
}
</script>
<asp:Label ID="LblName" runat="server" Text="Whats your name"></asp:Label>
<asp:TextBox ID="TxtNameBusiness" Width="322px" Height="30px" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredName" ValidationGroup="business"
runat="server" ErrorMessage="Please tell us your name." ControlToValidate="TxtNameBusiness"
CssClass="errMsg" Display="None"></asp:RequiredFieldValidator>
<asp:Button ID="BtnSumbit" runat="server" Text="Submit"
OnClientClick="displayValidationResult()" ValidationGroup="business" />
I've used some of the few ASP.NET client validation methods available. I've also renamed your controls to somewhat more meaningful and added a submit-button.
ASP.NET Validation in Depth
If your requirement is that you want to do this validation using the built-in ASP.Net validation controls, then you will need to use the ASP.Net CustomValidator control. This cannot be done using the ASP.Net RequiredFieldValidator control. To do the validation you specified, put a CustomValidator control on on your page so that the markup looks like this:
<asp:Label ID="Label1" runat="server" Text="Whats your name"></asp:Label>
<asp:TextBox ID="nameB" Width="322px" Height="30px" runat="server"></asp:TextBox>
<asp:CustomValidator ID="CustValidator" runat="server" ControlToValidate="nameB"
ValidateEmptyText="true" ErrorMessage="Please tell us your name."
onservervalidate="CustValidator_ServerValidate" Display="none" >**</asp:CustomValidator>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" onclick="btnSubmit_Click" CausesValidation="true" />
You then need to write your custom validator. The server-side validation code looks like this:
protected void CustValidator_ServerValidate(object source, ServerValidateEventArgs args)
{
if (string.IsNullOrWhiteSpace(args.Value))
{
Label1.Text = CustValidator.ErrorMessage;
args.IsValid = false;
}
else
{
Label1.Text = "Whats your name";
args.IsValid = true;
}
}
This custom validator will give you the behavior you desire.
In general when you use a CustomValidator control, you should do both server-side validation (for security) and client-side validation (for a better UI experience). To get client-side validation, you will need to write a client-side function in javascript and/or jQuery to do similar validation and then assign it to the ClientValidationFunction of the custom validator.
Further information on the CustomValidator control can be found in the MSDN documentation.
The MaskedEditExtender control that I am using is set up for a MaskType="DateTime" and the AcceptAMPM="true" but I need to know how a user can change the am/pm without having to type in A for AM and P for PM? Is there a way I can add arrows or something to this control so that it is more user-friendly when changing from AM to PM? My users aren't going to know that they need to type out the value for it to change.
<asp:TextBox ID="txtDateTime" runat="server"></asp:TextBox>
<asp:MaskedEditExtender ID="MaskedEditExtender1" runat="server"
TargetControlID="txtDateTime" MaskType="DateTime" Mask="99/99/9999 99:99"
MessageValidatorTip="true" CultureName="en-US" ErrorTooltipEnabled="True"
AcceptAMPM="true">
</asp:MaskedEditExtender>
I don't believe there is any way to change the functionality, at least not without a significant amount of work. If you need something that's a little more flexible, I would suggest looking at a jQuery Timepicker.
<script type="text/javascript">
//Set the default text to "PM"
var mee;
function pageLoad() {
//Please use your MaskedEditExtender's id or behaviorId.
mee = $find("MaskedEditExtender3");
//The target textbox control
var e = mee.get_element();
//Remove the focus event handler
if (mee._focusHandler) {
$removeHandler(e, "focus", mee._focusHandler);
}
//Add a new focus event handler which inherits from the old one.
mee._focusHandler = Function.createDelegate(mee, newFocus);
$addHandler(e, "focus", mee._focusHandler);
}
function newFocus() {
mee._onFocus();
if ((mee._MaskType == AjaxControlToolkit.MaskedEditType.Time || mee._MaskType == AjaxControlToolkit.MaskedEditType.DateTime) && mee.get_CultureAMPMPlaceholder() != "" && mee._getClearMask() == "") {
if (mee._AcceptAmPm) {
//The original code of default AM/PM text in function _onFocus() is:
//this.InsertAMPM(this.get_CultureAMPMPlaceholder().substring(0,1));
mee.InsertAMPM(meeTueEndCorp.get_CultureFirstLetterPM());
mee.setSelectionRange(0, 0);
}
}
}
</script>
<div>
<strong>Enter Time (format: <em>99:99:99</em>):</strong>
<br />
<asp:TextBox ID="TextBox3" runat="server" Width="130px" Height="16px" />
<ajaxToolkit:MaskedEditExtender ID="MaskedEditExtender3" runat="server" TargetControlID="TextBox3"
Mask="99:99:99" MessageValidatorTip="true" OnFocusCssClass="MaskedEditFocus"
OnInvalidCssClass="MaskedEditError" MaskType="Time" AcceptAMPM="True" ErrorTooltipEnabled="True" />
<ajaxToolkit:MaskedEditValidator ID="MaskedEditValidator3" runat="server" ControlExtender="MaskedEditExtender3"
ControlToValidate="TextBox3" IsValidEmpty="False" EmptyValueMessage="Time is required"
InvalidValueMessage="Time is invalid" Display="Dynamic" TooltipMessage="Input a time"
EmptyValueBlurredText="*" InvalidValueBlurredMessage="*" />
<br />
<em><span style="font-size: 8pt">Tip: Type 'A' or 'P' to switch AM/PM</span></em>
</div>
</form>
Check this link, may be this will help.
http://forums.asp.net/t/1339632.aspx
Or if you want to set the default value to PM. I have modified the code in the ajax control tool kit code and compile it again to work of default to PM.
Check this code on my blog.
http://blog.sumedh.in/post/2011/12/16/Ajax-Net-35-Control-Toolkit-MaskedEditExtender-Default-to-PM.aspx