Below is my code:
<asp:TextBox
ID="FromDateTextBox"
runat="server" />
<asp:ImageButton
ID="FromDateImageButton"
runat="server"
ImageUrl="~/images/calander.png" />
<ajaxkit:CalendarExtender
ID="FromDate"
runat="server"
TargetControlID="FromDateTextBox"
CssClass="CalanderControl"
PopupButtonID="FromDateImageButton"
Enabled="True" />
<ajaxkit:MaskedEditExtender
id="FromDateMaskedEditExtender"
runat="server"
targetcontrolid="FromDateTextBox"
Mask="99/99/9999"
messagevalidatortip="true"
onfocuscssclass="MaskedEditFocus"
oninvalidcssclass="MaskedEditError"
masktype="Date"
displaymoney="Left"
acceptnegative="Left"
errortooltipenabled="True" />
<ajaxkit:MaskedEditValidator
id="FromDateMaskedEditValidator"
runat="server"
controlextender="FromDateMaskedEditExtender"
controltovalidate="FromDateTextBox"
emptyvaluemessage="Date is required"
invalidvaluemessage="Date is invalid"
display="Dynamic"
tooltipmessage="Input a date"
emptyvalueblurredtext="*"
invalidvalueblurredmessage="*"
validationgroup="MKE" />
I've set Culture="auto" UICulture="auto" in #Page directive and EnableScriptGlobalization="true" EnableScriptLocalization="true" in script manager to have client culture specific date format in my textbox.
I also have a Go button on my page on which I will do a partial post back. So, I want to validate the FromDateTextBox in javascript when the Go button is clicked.
UPDATE
I know how to create a javascript click handler. But because masked editor is already validating the date on focus shift, I'm thinking there should be some boolean property (like IsValid) exposed by it which will allow me to see if the text box contains valid date.
FURTHER TRIALS
I also tried below code and Page_Validators[f].isvalid always returns true even when the date is invalid and MaskEditValidator shows me a red star near the Text box.
function isDateValid() {
var b = true;
for (var f = 0; f < Page_Validators.length; f++) {
if (!Page_Validators[f].isvalid)
b = false;
}
return b;
}
$('#GoButton').click(function() {
if (!isDateValid()) {
return false;
}
loadProducts();
});
Sorry do you mean that your MaskedEditValidator is not working when clicking GO button? Or if you want to write some js to check the date yourself? In this case you can add a client onclick event to GO button. One example in code behind is:
goButton.Attributes["onclick"] = "if (!CheckDate()) return false;";
And in the page file add a javascript function:
function CheckDate()
{
//check the date here
return isValid;
}
Now if the date is not valid,the CheckDate() will return false, the goButton event will also return without posting back.
I resolved it. Basically when there is an invalid date entered in the textbox the MaskedEditExtender changes the provided (OnInvalidCssClass="MaskedEditError") class of the textbox and I picked it up as a checking point for validation.
$('#GoButton').click(function () {
if($('#<%=FromDateTextBox.ClientID%>').hasClass('MaskedEditError')) {
return false;
}
}
Related
I am using a custom validator to validate a textbox content.
Everytime the user leaves this textbox, my client script is called, which is, in my case, a little bit annoying.
I want the validation only to be performed when the user clicks on a button given button (which is already happening).
Is there any way to avoid the validation to be performed on the OnChange event of the TextBox?
My code is here:
function isGroupNameUnique(sender, args) {
var valid = true;
var tokens = $('#hdnGroupNames').val().split(',');
var groupName = $('#<%= txtGroupName.ClientID %>').val();
$.each(tokens, function (i) {
if (groupName == this)
valid = false;
});
args.IsValid = valid;
}
<asp:TextBox ID="txtGroupName" runat="server" />
<asp:Button ID="btnAddGroup" runat="server" Text = "Add" onclick="btnAddGroup_Click" class="bGraySmaller" ValidationGroup="AddGroup"/>
<asp:CustomValidator ID="validatorGroupNameAlreadyExists" runat="server" ControlToValidate="txtGroupName" ErrorMessage="The Group Name has to be unique" ValidationGroup="AddGroup" ClientValidationFunction="isGroupNameUnique" />
Remove the ControlToValidate property on the CustomValidator(what is the only Validator where this property is not mandatory). Set the same ValidationGroup on the TextBox.
<asp:TextBox ID="txtGroupName" ValidationGroup="AddGroup" runat="server" />
<asp:CustomValidator ID="validatorGroupNameAlreadyExists" runat="server" ErrorMessage="The Group Name has to be unique" ValidationGroup="AddGroup" ClientValidationFunction="isGroupNameUnique" />
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
I have an asp.net web for with a few Validation controls on:
<div class="form-row">
<label>Email</label>
<asp:TextBox ID="txtUserName1" runat="server" onchange="validate(this)"> </asp:TextBox>
<asp:RequiredFieldValidator ID="reqUserName1" runat="server" ControlToValidate="txtUserName1"
ErrorMessage="- The email address field is required" Text="*" CssClass="error_star" Width="10px" ValidationGroup="Register"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RegularExpressionValidator2" CssClass="error_star" runat="server" ErrorMessage="- Invalid Email Address" Text="*"
ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*" ControlToValidate="txtUserName1"
ValidationGroup="Register"></asp:RegularExpressionValidator>
</div>
I have a button to submit the form
<asp:Button ID="cmdSubmit" runat="server" Text="Create Account" CssClass="small-button"
ValidationGroup="Register" CausesValidation="true" OnClientClick="validateForm()" OnClick="cmdSubmit_Click" />
The first time I hit the button some client side validation is run and my validateForm() method is not hit. for subsequent times I click the submit button my custom validation works fine.
How do I attach some custom JavaScript to the client side validation?
here' the javascript
function validateForm() {
$("input[type=text], input[type=password]", "#registerForm").each(function () {
validate(this)
});
}
function validate(control) {
// Change the colour of the border
for (var i = 0; i < control.Validators.length; i++) {
if (!control.Validators[i].isvalid) {
control.style.border = "1px solid red"
return;
}
}
control.style.border = "1px solid #E1D7CE"
}
The page wasn't validating, so the javascript was working but it thought all the controls where valid, I added this
if (!Page_ClientValidate("Register")) {
Page_ClientValidate("Register")
}
to validate the page.
You can use a custom validator
http://asp.net-tutorials.com/validation/custom-validator/
they work just like any other asp.net validators, accept you get to write the function that handles the validation and sets IsValid flag. This will in turn allow/prevent postback to occur.
1- use CustomValidator, hence all you validation logic will reside in your JavaScript Code, lets say you want to validate TextBox for number > 12, javascript code would be like:
function Validate(src, eventargs)
{
var control = Document.GetElementByID(src);
if(control.value > 12)
eventargs.IsValid = true;
else
eventargs.IsValid = false;
}
2- Use CustomValidator's ClientValidationFunctionProperty set to ="Validate" (the JavaScript Function)
when you try to do any postback, then the Page.Validators collection is evaluated and so your CustomValidator
I've got a drop-down where the user selects a Country. It is a required "field".
Next to it, there is a textfield named State. If the user selects US, then the field State is required. If the user selects e.g. Sweden, the State is not required, since Sweden has no states.
Example code:
<asp:DropDownList runat="server" ID="Country"></asp:DropDownList>
<asp:RequiredFieldValidator ControlToValidate="Country"
runat="server" Display="Static" ErrorMessage="Required field" />
<asp:TextBox runat="server" ID="State"></asp:TextBox>
<asp:CustomValidator ClientValidationFunction="DoesntGetFiredIfStateIsEmpty"
runat="server" Display="Static" ErrorMessage="Required field" />
<!-- SO, RATHER THIS TOGETHER WITH CONDITIONAL FIRING -->
<asp:RequiredFieldValidator ControlToValidate="State"
runat="server" Display="Static" ErrorMessage="Required field" />
My question to you is: How can I make this CustomValidator fire validation when it is empty?
Or put simplier: How can I make a RequiredValidator fire conditionally?
Or simplest: How can I enable/disable a RequiredValidator on client-side?
Try doing this with javascript to enable and disable validators
ValidatorEnable(RequiredFieldValidatorId, false);
Check out this question that I answered.
Asp.net has a client side javascript function to manage the validators, the "ValidatorEnable" function,
ValidatorEnable(RequiredFieldValidatorId, false);
you can call it simply using javascript, you must send the validator object to the function (not only its id).
if (x==y) {
ValidatorEnable($('#<%=rfvFamily.ClientID %>'), false);
} else {
ValidatorEnable($('#<%=rfvFamily.ClientID %>'), true);
}
or
if (x==y) {
ValidatorEnable(document.getElementById("<%=rfvFamily.ClientID %>", false);
} else {
ValidatorEnable(document.getElementById("<%=rfvFamily.ClientID %>", true);
}
full documnet on:
http://msdn.microsoft.com/en-us/library/Aa479045#aspplusvalid_clientside
another way is to Set in your DropDownList CausesValidation="false" to avoid that the validators block a postback when you change the DropDownList entry.
(*) Remember this function is for client side, for disabling validator in server side, you must to disable validator on page postback too.
if (IsPostBack){
if (x==y) {
rfvFamily.Enabled = false;
}
}
Does anyone know why a client-side javascript handler for asp:CheckBox needs to be an OnClick="" attribute rather than an OnClientClick="" attribute, as for asp:Button?
For example, this works:
<asp:CheckBox runat="server" OnClick="alert(this.checked);" />
and this doesn't (no error):
<asp:CheckBox runat="server" OnClientClick="alert(this.checked);" />
but this works:
<asp:Button runat="server" OnClientClick="alert('Hi');" />
and this doesn't (compile time error):
<asp:Button runat="server" OnClick="alert('hi');" />
(I know what Button.OnClick is for; I'm wondering why CheckBox doesn't work the same way...)
That is very weird. I checked the CheckBox documentation page which reads
<asp:CheckBox id="CheckBox1"
AutoPostBack="True|False"
Text="Label"
TextAlign="Right|Left"
Checked="True|False"
OnCheckedChanged="OnCheckedChangedMethod"
runat="server"/>
As you can see, there is no OnClick or OnClientClick attributes defined.
Keeping this in mind, I think this is what is happening.
When you do this,
<asp:CheckBox runat="server" OnClick="alert(this.checked);" />
ASP.NET doesn't modify the OnClick attribute and renders it as is on the browser. It would be rendered as:
<input type="checkbox" OnClick="alert(this.checked);" />
Obviously, a browser can understand 'OnClick' and puts an alert.
And in this scenario
<asp:CheckBox runat="server" OnClientClick="alert(this.checked);" />
Again, ASP.NET won't change the OnClientClick attribute and will render it as
<input type="checkbox" OnClientClick="alert(this.checked);" />
As browser won't understand OnClientClick nothing will happen. It also won't raise any error as it is just another attribute.
You can confirm above by looking at the rendered HTML.
And yes, this is not intuitive at all.
Because they are two different kinds of controls...
You see, your web browser doesn't know about server side programming. it only knows about it's own DOM and the event models that it uses... And for click events of objects rendered to it. You should examine the final markup that is actually sent to the browser from ASP.Net to see the differences your self.
<asp:CheckBox runat="server" OnClick="alert(this.checked);" />
renders to
<input type="check" OnClick="alert(this.checked);" />
and
<asp:CheckBox runat="server" OnClientClick="alert(this.checked);" />
renders to
<input type="check" OnClientClick="alert(this.checked);" />
Now, as near as i can recall, there are no browsers anywhere that support the "OnClientClick" event in their DOM...
When in doubt, always view the source of the output as it is sent to the browser... there's a whole world of debug information that you can see.
You are right this is inconsistent. What is happening is that CheckBox doesn't HAVE an server-side OnClick event, so your markup gets rendered to the browser. http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.checkbox_events.aspx
Whereas Button does have a OnClick - so ASP.NET expects a reference to an event in your OnClick markup.
For those of you who got here looking for the server-side OnClick handler it is OnCheckedChanged
I was cleaning up warnings and messages and see that VS does warn about it:
Validation (ASP.Net): Attribute 'OnClick' is not a valid attribute of element 'CheckBox'. Use the html input control to specify a client side handler and then you won't get the extra span tag and the two elements.
Asp.net CheckBox is not support method OnClientClick.
If you want to add some javascript event to asp:CheckBox you have to add related attributes on "Pre_Render" or on "Page_Load" events in server code:
C#:
private void Page_Load(object sender, EventArgs e)
{
SomeCheckBoxId.Attributes["onclick"] = "MyJavaScriptMethod(this);";
}
Note: Ensure you don't set AutoEventWireup="false" in page header.
VB:
Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
SomeCheckBoxId.Attributes("onclick") = "MyJavaScriptMethod(this);"
End Sub
You can do the tag like this:
<asp:CheckBox runat="server" ID="ckRouteNow" Text="Send Now" OnClick="checkchanged(this)" />
The .checked property in the called JavaScript will be correct...the current state of the checkbox:
function checkchanged(obj) {
alert(obj.checked)
}
You can assign function to all checkboxes then ask for confirmation inside of it. If they choose yes, checkbox is allowed to be changed if no it remains unchanged.
In my case I am also using ASP .Net checkbox inside a repeater (or grid) with Autopostback="True" attribute, so on server side I need to compare the value submitted vs what's currently in db in order to know what confirmation value they chose and update db only if it was "yes".
$(document).ready(function () {
$('input[type=checkbox]').click(function(){
var areYouSure = confirm('Are you sure you want make this change?');
if (areYouSure) {
$(this).prop('checked', this.checked);
} else {
$(this).prop('checked', !this.checked);
}
});
});
<asp:CheckBox ID="chk" AutoPostBack="true" onCheckedChanged="chk_SelectedIndexChanged" runat="server" Checked='<%#Eval("FinancialAid") %>' />
protected void chk_SelectedIndexChanged(Object sender, EventArgs e)
{
using (myDataContext db = new myDataDataContext())
{
CheckBox chk = (CheckBox)sender;
RepeaterItem row = (RepeaterItem) chk.NamingContainer;
var studentID = ((Label) row.FindControl("lblID")).Text;
var z = (from b in db.StudentApplicants
where b.StudentID == studentID
select b).FirstOrDefault();
if(chk != null && chk.Checked != z.FinancialAid){
z.FinancialAid = chk.Checked;
z.ModifiedDate = DateTime.Now;
db.SubmitChanges();
BindGrid();
}
gvData.DataBind();
}
}
One solution is with JQuery:
$(document).ready(
function () {
$('#mycheckboxId').click(function () {
// here the action or function to call
});
}
);