Can I change default for MaskedEditExtender am/pm? - asp.net

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

Related

How can I achieve the effect of multiple validation groups on a single validation control?

I need to be able to apply multiple validation groups to some of the controls on my page, because for each of the three submit "modes", there is a different set of required fields.
I have three submit buttons, and each one has its own validation group (reject, approve, and save). "Reject" doesn't actually have any required fields currently, but may in the future. "Save" only requires "first name" and "last name", while "approve" requires "first name", "last name", as well as "group name".
I tried simply putting multiple validation groups in the attribute value (as in the code below), but the validation didn't fire at all.
I also tried not specifying a group at all in an attempt to just have the validation always fire, but again again, it didn't fire at all.
<div>
<label for='<%= txt_FirstName.ClientID %>'>First Name</label>
<asp:TextBox ID="txt_FirstName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfv_FirstName" runat="server" text="Required"
ControlToValidate="txt_FirstName" ValidationGroup="approve save">
</asp:RequiredFieldValidator>
</div>
<div>
<label for='<%= txt_LastName.ClientID %>'>Last Name</label>
<asp:TextBox ID="txt_LastName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfv_LastName" runat="server" text="Required"
ControlToValidate="txt_LastName" ValidationGroup="approve save">
</asp:RequiredFieldValidator>
</div>
<div>
<label for='<%= ddl_GroupName.ClientID %>'>Group Name</label>
<asp:DropDownList ID="ddl_GroupName" runat="server"></asp:DropDownList>
<asp:RequiredFieldValidator ID="rfv_GroupName" runat="server" text="Required"
ControlToValidate="ddl_GroupName" ValidationGroup="approve">
</asp:RequiredFieldValidator>
</div>
<div>
<asp:Button ID="btn_Reject" runat="server" Text="Reject"
ValidationGroup="reject" OnClick="btn_Reject_Click" />
<asp:Button ID="btn_Approve" runat="server" Text="Approve"
ValidationGroup="approve" OnClick="btn_Approve_Click" />
<asp:Button ID="btn_Save" runat="server" Text="Save"
ValidationGroup="save" OnClick="btn_Save_Click" />
</div>
I'm certain I can achieve the desired effect with some additional code, or duplicated validator controls for each validation group, but I was hoping the webforms framework would have a simpler, built-in way to do this.
UPDATE (2018-01-02):
The question "Is it possible to assign Multiple Validation Groups to a single Validation Control?" is a special case of my own. It has a single control in multiple groups, whereas I have multiple controls with multiple overlapping groups. Additionally, the answer proposes having a validation control for each input/group combination. This is a terrible solution because, among other things, it violates the DRY (don't repeat yourself) programming principle and makes maintenance/enhancements more difficult.
The above also links the question "How to validate against Multiple validation groups?". That question is a completely different issue (validation groups within validation groups), and its answer proposes custom javascript that would need to be written for every submit button, on every page that requires multiple validation groups.
I am looking for a general case solution that I can write/implement once and apply to the entirety of the web application, and thus I do not consider my question a duplicate of the above mentioned questions.
UPDATE (2018-01-03):
Between other questions/articles I've encountered while researching my problem, as well as the gracious assistance of a.bajorinas and Sunil, I've established that it is not possible to have multiple validation groups on a validation control out-of-the-box, and custom code will be required to achieve the desired effect. I've updated the question accordingly, to assist anyone looking to achieve this in the future.
I'll be testing a solution that incorporates elements from both a.bajorinas' and Sunil's answers and will hopefully be able to provide an update afterward.
The only thing I can think of for your desired use case, is setting ValidationGroup for your validators in code behind on button click, keep in mind that this would first perform a postback and then validate the controls which might not be ok for you.
protected void btn_save_click(object sender, EventArgs e){
rfv_FirstName.ValidationGroup = "save";
Page.Validate("save");
if (Page.IsValid)
{
//logic if validators pass
}
}
This will let you reuse validators for multiple groups.
Also in my linked posted, one of the comments to the selected answer is "It is not possible to assign multiple groups to a validation control"
ASP.Net does not support multiple validation groups. However, with a little bit of JavaScript code you can make it support multiple validation groups.
What you need to do is override the standard JavaScript function of IsValidationGroupMatch. This function is part of the standard validation library in ASP.Net.
At bottom of your aspx page, just add the script tag given below. Note that this script is just before closing form, body and html tags, which is important when overriding a JavaScript function.
<script type="text/javascript">
window["IsValidationGroupMatch"] = function (control, validationGroup) {
if ((typeof (validationGroup) == "undefined") || (validationGroup == null)) {
return true;
}
var controlGroup = "";
var isGroupContained = false;
if (typeof (control.validationGroup) == "string") {
controlGroup = control.validationGroup;
var controlGroupArray = [];
if (validationGroup.indexOf(",") > -1) {
controlGroupArray = validationGroup.split(",");// validationGroup.split(",");
}
for (var i = 0; i < controlGroupArray.length; i++) {
if (controlGroupArray[i].trim() == controlGroup.trim()) {
isGroupContained = true;
}
}
}
return (controlGroup == validationGroup || isGroupContained);
}
</script>
</form>
</body>
</html>
Once you do this, then you can add a comma delimited list of validation groups for the button that validates multiple validation groups as in example below. In example below a button with id of btnMultipleValidationGroups is validating group1 as well as group2.
<div>
TextBox1 :
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="TextBox1 needs input" ControlToValidate="TextBox1" ForeColor="Red" ValidationGroup="group1"></asp:RequiredFieldValidator>
<br />
<br />
TextBox2 :
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="TextBox2 needs input" ControlToValidate="TextBox2" ForeColor="Red" ValidationGroup="group2"></asp:RequiredFieldValidator>
<br />
<br />
TextBox3 :
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ErrorMessage="TextBox3 needs input" ControlToValidate="TextBox3" ForeColor="Red" ValidationGroup="group3"></asp:RequiredFieldValidator>
<br />
<br />
</div>
<asp:Button ID="btnMultipleValidationGroups" runat="server" Text="Validate group1 and group2" ValidationGroup="group1,group2" OnClick="btnMultipleValidationGroups_Click" />
<asp:Button ID="btnGroup1" runat="server" Text="Validate only group1" ValidationGroup="group1" OnClick="btnGroup1_Click" />
<asp:Button ID="btnGroup2" runat="server" Text="Validate only group2" ValidationGroup="group2" OnClick="btnGroup2_Click" />

Run ASP.Net Custom Validator only on click of one of multiple buttons on the page

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

ASP.net Custom Validator message not displaying

I have a div which acts like a modal popup. Inside that, I need a validation for which I setup a custom validator. But the message doesn't get fired, though the alert box does.
My code:
if ((oldFromTime <= newFromTime) && (oldToTime > newFromTime)) {
alert("Choose time ahead of the ones saved earlier.!");
arguments.IsValid = false;
}
else {
arguments.IsValid = true;
}
And my custom validator
<asp:CustomValidator id="cboToTimeMins_CustomValidator" ControlToValidate="cboToTimeMins" ClientValidationFunction="validateTime"
Display="static" ErrorMessage="Selected time range falls in the range of the ones saved earlier...! Choose another." runat="server" ValidationGroup="Timetable"/>
cboToTimeMins is my dropdown box, and I need to set the validation message based on the value selected from it.
Is there something wrong in my code?
P.S. I am in need of only CLIENT SIDE validation.
Here's my solution. I removed the custom validator for the Dropdown and added it to a button instead. Also, I removed the alert message in the Javascript function.
Here's my example solution
<td class="normal">Price<span class="required">*</span></td>
<td class="normal" colspan="6">
<asp:TextBox ID="txtPrice" CssClass="text" Enabled="true" runat="server" MaxLength="10" Width="100px" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="txtPrice"
ErrorMessage="* Please Input Your Price" Display="Dynamic" ValidationGroup="hdrValidation"/>
</td>
And you need to validate
Page.Validate("hdrValidation")
If Not Page.IsValid Then Exit Sub

customvalidator always isvalid=true

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.

Required field validator not working

I have used a required field validator followed by a regular expression validator but the required field validator is not working.....
<asp:TextBox ID="txtSummary" runat="server" TextMode="MultiLine" Width="700px"
CssClass="txtStyle" Font-Names="Arial" MaxLength="1000"
ValidationGroup="Valtxt" TabIndex="2" Rows="4">
</asp:TextBox>
<asp:RegularExpressionValidator ID="regValSummary" runat="server"
ControlToValidate="txtSummary" Display="Dynamic"
ValidationExpression="[^<>&#!]*" ValidationGroup="Valtxt">
Invalid characters(<>&#!) are not allowed
</asp:RegularExpressionValidator>
<asp:RequiredFieldValidator ID="reqvalSummary" runat="server"
ControlToValidate="txtSummary" ErrorMessage="Summary is required"
ValidationGroup="Valtxt" Display="Dynamic">
</asp:RequiredFieldValidator>
can anyone sees the problem???
The RequiredFieldValidator is triggered by the client side onchange event. It sounds like you're expecting it to be triggered by the onblur event, such that tabbing away from the textbox would fire the validation.
Before jumping to that, I suspect this is what you are seeing and to validate that it's actually working you need to trigger onchange. To do so, enter some text in the textbox, tab away, tab back to it, clear the textbox, then tab away once more. You should now see the RequiredFieldValidator's error message since it's contents have changed.
Back to the onblur issue. To accomplish that behavior you could add the onblur attribute in your code-behind and have it call the ValidatorValidate(...) JavaScript method as follows:
void Page_Load(object sender, EventArgs e)
{
txtSummary.Attributes.Add("onblur", "ValidatorValidate(" + reqvalSummary.ClientID + ")");
}
Alternately, you could accomplish the same thing in markup. First, add this script block:
<script type="text/javascript">
function rfvBlur() {
var rfv = document.getElementById("<%= reqvalSummary.ClientID %>");
ValidatorValidate(rfv);
}
</script>
Second, update the <asp:TextBox.../> markup by adding onblur="rfvBlur()" so that it now looks like this:
<asp:TextBox ID="txtSummary" runat="server" TextMode="MultiLine" Width="700px" CausesValidation="true"
CssClass="txtStyle" Font-Names="Arial" MaxLength="1000" ValidationGroup="Valtxt"
TabIndex="2" Rows="4" onblur="rfvBlur()" />
Yet another option is to validate the entire ValidationGroup by adding the following attribute to your <asp:TextBox.../> markup (no additional script block needed):
onblur="Page_ClientValidate('Valtxt')"
Adding this line to <appSettings> section of web.config worked for me (I had a problem when all validators stopped working when project was upgraded to .NET 4.5):
<add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
Source:
http://forums.asp.net/t/1876231.aspx?ASP+Net+4+5+Validation+Controls+not+working+with+AJAX+ToolkitScriptManager1
Why don't you change the regular expression of the "RegEx" validator to check if the textbox is empty instead of use another validator?
Anyway probabily you have not specify ValidationGroup="Valtxt" for the button or the control that raise the postback. Just add ValidationGroup="Valtxt" to the button or the server control that raise the post to the page
I put the following at the top of my btn_Click event handler (to prevent further code execution) and upon 'return', the rfv messages show...
Page.Validate("your validation group");
if (!Page.IsValid)
{
return;
}
<asp:TextBox ID="txtSummary" runat="server" TextMode="MultiLine" Width="700px"
CssClass="txtStyle" Font-Names="Arial" MaxLength="1000"
TabIndex="2" Rows="4">
</asp:TextBox>
<asp:RegularExpressionValidator ID="regValSummary" runat="server"
ControlToValidate="txtSummary" ErrorMessage="Invalid characters(<>&#!) are not allowed" Text="*"
ValidationExpression="[^<>&#!]*" ValidationGroup="Valtxt">
</asp:RegularExpressionValidator>
<asp:RequiredFieldValidator ID="reqvalSummary" runat="server"
ControlToValidate="txtSummary" ErrorMessage="Summary is required" Text="*"
ValidationGroup="Valtxt">
</asp:RequiredFieldValidator>

Resources