Override ValidatorOnChange(event) in Javascript - c#

i have asp.net webapplication.
i have used RequiredFieldValidator to validate the Textbox.
i have used ValidatorOnChange(event) onblur event of textbox as follows :
<asp:TextBox ID="txtFname" runat="server" CssClass="txtBoxWidthMiddle txtSingleline txtBack-Color txtRequireBorder-Color required"
MaxLength="50" TabIndex="2" onblur="ValidatorOnChange(event);"></asp:TextBox>
<br />
<asp:RequiredFieldValidator ID="rfvFname" runat="server" ControlToValidate="txtFname"
ErrorMessage="First Name is required" ValidationGroup="a" Display="Dynamic"></asp:RequiredFieldValidator>
my question is is it possible to override ValidatorOnChange(event) method ? i want to call a function based on ValidatorOnChange(event) method return result(true or false).
Thanks

In the onblur event of the textbox you can use any js function. For example, I created a function that is the one that actually calls the ValidatorOnChange(...). You could change the ValidatorOnChange(...) function to match your needs.
<asp:TextBox ID="TextBox1" runat="server" onblur="myValidatorOnChange(event);"></asp:TextBox>
<script type="text/javascript">
function myValidatorOnChange(event) {
var result = ValidatorOnChange(event);
return result;
}
</script>

Related

Use server side and client side validation simultaneously on a single form in C#

I have a form (in aspx page) where I am using server side validations (validation controls) and jQuery validations on the same form.
On Textboxes I am using server side validations and on submit button I am using jQuery validation.
I having problem in using both together.
Form:-
<form id="form1" runat="server">
<label>Start Date: </label>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" ControlToValidate="txtstartDate" ForeColor="Red" Text="*" ValidationGroup="onSave" runat="server" ErrorMessage="Enter start date...!!"></asp:RequiredFieldValidator>
<asp:TextBox ID="txtStartDate" runat="server" CssClass="form-control mytxtCalendar" placeholder="Start Date.."></asp:TextBox>
<label> End Date:</label>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" ControlToValidate="txtEndDate" ForeColor="Red" Text="*" ValidationGroup="onSave" runat="server" ErrorMessage="Enter end date...!!"></asp:RequiredFieldValidator>
<asp:TextBox ID="txtEndDate" runat="server" CssClass="form-control mytxtCalendar" placeholder="End Date.."></asp:TextBox>
<asp:Button ID="btnSaveShift" CssClass="btn btn-default" runat="server" Text="Save" ValidationGroup="onSave" OnClick="btnSaveShift_Click" OnClientClick="CheckDateTimes();" />
<asp:ValidationSummary ID="vlsAdd" ValidationGroup="onSave" ForeColor="Red" ShowMessageBox="true" ShowSummary="false" runat="server" />
</form>
jQuery Code:-
function CheckDateTimes() {
var Frm_Date = $("#<%=txtStartDate.ClientID %>").val();
var To_Date = $("#<%=txtEndDate.ClientID %>").val();
if (Frm_Date.length > 0 && To_Date.length > 0) {
if (parseDate(Frm_Date) > parseDate(To_Date)) {
alert('Start date can not be greater than to date...!!');
$("#<%=txtStartDate.ClientID %>").focus();
}
}
}
I have also tried below jQuery functions but these stops server side validations.
$("#btnSaveShift").click(function(evt){
var Frm_Date = $("#<%=txtStartDate.ClientID %>").val();
var To_Date = $("#<%=txtEndDate.ClientID %>").val();
if (Frm_Date.length > 0 && To_Date.length > 0) {
if (parseDate(Frm_Date) > parseDate(To_Date)) {
alert('Start date can not be greater than to date...!!');
$("#<%=txtStartDate.ClientID %>").focus();
evt.preventDefault();
}
}
});
This as well:-
<asp:Button ID="btnSaveShift" CssClass="btn btn-default" runat="server" Text="Save" ValidationGroup="onSave" OnClick="btnSaveShift_Click" OnClientClick="return CheckDateTimes();" />
function CheckDateTimes() {
var Frm_Date = $("#<%=txtStartDate.ClientID %>").val();
var To_Date = $("#<%=txtEndDate.ClientID %>").val();
if (Frm_Date.length > 0 && To_Date.length > 0) {
if (parseDate(Frm_Date) > parseDate(To_Date)) {
alert('Start date can not be greater than to date...!!');
$("#<%=txtStartDate.ClientID %>").focus();
return false;
}
}
return true;
}
If you need to use both OnClick and OnClientClick together with the same button then add a return true or false to OnClientClick function. Please check this link
example
you need to change CheckDateTimes method to return bool value, then you can change JS method call as OnClientClick="return CheckDateTimes();" if this return true only it will call server side. if you need to call server side validation always then return true from the javascript method.
check Asp .NET Button - OnClientClick="return function()" vs OnClientClick="function()"

Clear Specific Textboxes ASPX page

I'm having trouble trying to clear these banking and routing numbers that are in a textbox on an aspx page. I've seen it used where they would just specify the ID of the textbox and do a textbox.text = String.Empty(). But that doesn't seem to work here. Maybe I'm using the wrong ID?? I also tried using JQuery .val("") but that didn't seem to work either.
Here's the code, i'd like to clear both Routing and Account text fields on click of a button:
<div id="DivUser1BankInfo" class="labelAndTextboxContainer">
<div class="labelContainer">
<asp:Label CssClass="rightFloat" ID="User1LabelRoutingNumber" runat="server" Text="Routing #:"></asp:Label><br />
</div>
<div class="textboxContainer">
<asp:TextBox ID="User1TextRoutingNumber" CssClass="leftFloat " runat="server" Font-Size="Smaller" Width="180px"
Text='<%# Bind("User1BankRoutingNumber") %>'
Visible='<%# ApexRemington.BLL.VendorBLL.ShowUser1BankInfo((string)Eval("User1BankInfoEditUser")) %>' /><br />
</div>
<div class="labelContainer">
<asp:Label CssClass="rightFloat" ID="User1LabelAccountNumber" runat="server" Text="Account #:"></asp:Label><br />
</div>
<div class="textboxContainer">
<asp:TextBox ID="User1TextAccountNumber" CssClass="leftFloat " runat="server" Font-Size="Smaller" Width="180px"
Text='<%# Bind("User1BankAccountNumber") %>'
Visible='<%# ApexRemington.BLL.VendorBLL.ShowUser1BankInfo((string)Eval("User1BankInfoEditUser")) %>' /><br />
</div>
<button type="button" id="clearButton1">Clear</button>
<div class="button">
<asp:Button ID="User1ClearBankInfo" runat="server" Text="Reset"
Visible='<%# ApexRemington.BLL.VendorBLL.ShowUser1BankInfo((string)Eval("User1BankInfoEditUser")) %>' OnClick="clearFields_btn"/><br />
</div>
The OnClick= "clearFields_btn" code behind =
protected void clearFields_btn(object sender, EventArgs e)
{
}
Thanks for any help!
I haven't worked with ASP.NET in a little while, but I think you may want the OnClientClick event, not OnClick. OnClientClick is for client-side code (your jQuery/JavaScript) and OnClick is for server-side code (your C# or VB.NET).
You'd also want your OnClientClick event method to return false, or the server-side code will also fire.
So I think you want something like:
<asp:Button ID="User1ClearBankInfo" runat="server" Text="Reset"
Visible='<%# ApexRemington.BLL.VendorBLL.ShowUser1BankInfo((string)Eval("User1BankInfoEditUser")) %>
OnClientClick="clearText();"/>
And then clearText would look like this:
<script>
function clearText()
{
//our two IDs
$('input[id*="User1TextRoutingNumber"]').each(function(index) {
$(this).val('');
});
$('input[id*="User1TextAccountNumber"]').each(function(index) {
$(this).val('');
});
return false;
}
</script>
EDIT: shoot, I see my mistake. Fixed the code to clear the text of the textbox, not the button ("this").
Edit: removed the space from the "clear" text val.
EDIT: Made search a little more flexible, less dependent on GridView or no GridView.
Try this
<script>
var clear = function(textboxID){$('input[id*=' + textboxID + ']').val('');};
return false;
</script>
<button id="btClearText" onclick="javascript:return clear('txtName');">
but if you need a more specific answer then please post more information
You need something like this. Assuming you want a client side solution (not very clear from your question).
<script type="text/javascript">
function clearTextBox() {
document.getElementById("<%= User1TextRoutingNumber.ClientID %>").value = "";
//or
$("#<%= User1TextRoutingNumber.ClientID %>").val("");
}
</script>
The <%= User1TextRoutingNumber.ClientID %> will ensure you get the correct ID for javascript/jQuery.
A server side solution would be:
protected void clearFields_btn(object sender, EventArgs e)
{
for (int i = 0; i < GridView1.Rows.Count; i++)
{
TextBox tb = GridView1.Rows[i].FindControl("User1TextAccountNumber") as TextBox;
tb.Text = "";
}
}

asp.net button event not firing when using jquery and html5 required attribute in textbox

I have a problem with asp.net c# button event as it doesn't fire. In my form I use html 5 required attributes for text boxes and a jQuery password strengh meter for the password field (this password field also have a required attribute).
Aspx
<asp:TextBox ID="txtNewPwd" required="required" runat="server" CssClass="form-control" ToolTip="New Password" placeholder="New Password"></asp:TextBox>
<asp:Label ID="lblResult" runat="server" />
<asp:HiddenField ID="hdnResult" runat="server" />
<asp:Button ID="btnSubmit" runat="server" CssClass="btn btn-success custombutton" Text="SAVE" OnClick="btnSubmit_Click"/>
Script
<script type="text/javascript">
$(document).ready(function () {
$('#MainContent_txtNewPwd').keyup(function () {
$('#MainContent_lblResult').html(passwordStrength($('#MainContent_txtNewPwd').val(), $('#MainContent_hdnUserID').val()))
$('#MainContent_hdnResult').val(passwordStrength($('#MainContent_txtNewPwd').val(), $('#MainContent_hdnUserID').val()))
})
});
var parameter = Sys.WebForms.PageRequestManager.getInstance();
parameter.add_endRequest(function () {
$('#MainContent_txtNewPwd').keyup(function () {
$('#MainContent_lblResult').html(passwordStrength($('#MainContent_txtNewPwd').val(), $('#MainContent_hdnUserID').val()))
$('#MainContent_hdnResult').val(passwordStrength($('#MainContent_txtNewPwd').val(), $('#MainContent_hdnUserID').val()))
})
});
</script>
Add to your page "runat="server"" script, and there handle your event. Then you can work with required property OnClick

How to pass a hidden field value on javascript function inside repeater control

I tried a lot but couldn't figure it out. I wanted to pass data on my javascript function.
I am saving data on hidden filed. what I want as soon I click on my button it will call javascript function & pass my hidden field vlaue.
<asp:Repeater ID="rptGallary" runat="server" >
<ItemTemplate>
<asp:HiddenField ID="hfsportsmanfeedid" runat="server" value='<%# DataBinder.Eval(Container.DataItem,"SportsmanFeedId") %>'/>
<asp:Button ID="btnLike" runat="server" Text="Like" OnClientClick="Test("How to pass here"));" />
</ItemTemplate>
</asp:Repeater>
Thanks for your help.
You just need to pass the clicked element on Test button click
Try with this code:
HTML/ASPX Markup
<asp:Button ID="btnLike" runat="server" Text="Like"
OnClientClick="Test(this);" />
Javascript
function Test(element){
var $btn = $(element) // Gets clicked button
var hiddenBValue = $btn.prev().val(); // Gets hidden element value
}
Docs
prev()
This should work!
You can pass it like,
<asp:HiddenField ID="hfsportsmanfeedid" runat="server" value='<%# DataBinder.Eval(Container.DataItem,"SportsmanFeedId") %>'/>
<asp:Button ID="btnLike" runat="server" Text="Like" OnClientClick="Test('<%# DataBinder.Eval(Container.DataItem,\"SportsmanFeedId\") %>'));" />
SCRIPT
function Test(value){
alert(value);
}
Or use prev() like,
<asp:Button ID="btnLike" runat="server" Text="Like" OnClientClick="Test(this));" />
SCRIPT
function Test(ths){
alert($(ths).prev().val());
}
Do it like this-
<asp:Button ID="btnLike" runat="server" Text="Like" OnClientClick="javascript:Test(document.getElementById('hfsportsmanfeedid').value);" />
get the value of hidden field from repeater rptGallary_ItemCommand event and pass that to java script
protected void rptGallary_ItemCommand(object source, RepeaterCommandEventArgs e)
{
//add command name to btnLike button let it bet test here
if (e.CommandName == "test")
{
HiddenField hiddenfield = (HiddenField)e.Item.Parent.Parent.FindControl("hfsportsmanfeedid");
//pass that to javascript
}
}

Required field validator for User control not working

Hi I have created user control for re-sizable text box.
<asp:Panel ID="PanelText" runat="server" CssClass="frameText">
<asp:TextBox runat="server" ID="TextBoxResizable" CssClass="noborder" Width="100%"
Height="100%" TextMode="MultiLine">
</asp:TextBox>
</asp:Panel>
<cc1:ResizableControlExtender ID="ResizableTextBoxExtender" runat="server" TargetControlID="PanelText"
ResizableCssClass="resizingText" HandleCssClass="handleText" OnClientResizing="OnClientResizeText" />
And have created Validator property for this control like:
[ValidationProperty("Text")]
public partial class ResizableTextBoxControl : System.Web.UI.UserControl
{ public string Validator
{
get { return this.TextBoxResizable.Text; }
}
protected void Page_Load(object sender, EventArgs e)
{
}
}
In aspx page I am using this control like:
<uc1:ResizableTextBoxControl ID="tbDescription" MinimumHeight="50" MinimumWidth="100"
MaximumHeight="300" MaximumWidth="400" runat="server" onKeyPress="javascript:Count(this,1500);" onKeyUp="javascript:Count(this,1500);" ValidationGroup="vgSubmit" ></uc1:ResizableTextBoxControl>
<asp:RequiredFieldValidator ID="rfvDescription" runat="server" controlToValidate="tbDescription" ValidationGroup="vgSubmit" ErrorMessage="Description" Text="*" ForeColor="Red" SetFocusOnError="True"></asp:RequiredFieldValidator>
When I click on submit, "tbDescription" does not appear to be mandatory.
What can be wrong with the code?
EDIT
Ok...I got what was the problem, one control was hidden, and required field validator for that control was not disabled, I did it using jquery and now everything is fine except asterics.. I dont understand why asterics are not visible..
try placing your validator to your controlle especially if you just try to validate one textbox
<asp:Panel ID="PanelText" runat="server" CssClass="frameText">
<asp:TextBox runat="server" ID="TextBoxResizable" CssClass="noborder" Width="100%"
Height="100%" TextMode="MultiLine">
</asp:TextBox>
<asp:RequiredFieldValidator
ID="rfvDescription" runat="server" controlToValidate="TextBoxResizable"
ValidationGroup="vgSubmit"
ErrorMessage="Description" Text="*"
ForeColor="Red" SetFocusOnError="True">
</asp:RequiredFieldValidator
</asp:Panel>
<cc1:ResizableControlExtender ID="ResizableTextBoxExtender"
runat="server" TargetControlID="PanelText"
ResizableCssClass="resizingText" HandleCssClass="handleText OnClientResizing="OnClientResizeText" />
in to the user controller it might not be recognized after the page is rendered.
try using Page.IsValid in your Submit button event.
if (!Page.IsValid) {
return;
}
Sorry for all the trouble,
There was one control on page which was hidden and required field validator for that control was not disabled. I disabled it using jQuery like
$(document).ready(function () {
if (!$("#<%=TextBoxResizable.ClientID %>").is(":visible")) {
ValidatorEnable(<%=rfvTextBoxResizable.ClientID %>, false);
}
})
Asteric is visible after placing required field validator outside Panel.

Categories