Required Field Validator issue validating TextBox value - c#

I have a TextBox which i use to store a url to applied a <asp:HyperLink> control. What i want to do is fire off the RequiredFieldValidator when the TextBox.Text value is empty and the user clicks save. As far as i can tell, my logic is OK, but the validator isn't firing off?
Here's the markup:
<div class="frmRow">
<div class="frmControls">
<asp:Label ID="lblLink" AssociatedControlID="txtImgUrl" runat="server" Text="Image URL"></asp:Label>
<asp:RequiredFieldValidator ID="imgUrlValidator" runat="server" ControlToValidate="txtImgUrl" ErrorMessage="Enter a Valid URL" />
<asp:TextBox ID="txtImgUrl" runat="server" />
</div>
<div class="clearBoth"></div>
</div>
Here is the code to check a valid absolute URL which is inside my btnSave event:
Uri url;
if (!string.IsNullOrEmpty(txtImgUrl.Text))
{
txtImgUrl.Text = Uri.TryCreate(txtImgUrl.Text, UriKind.Absolute, out url) ? url.AbsoluteUri : string.Empty;
}
Save button markup:
<br class="clearBoth" />
<asp:Button ID="btnSave" Text="Save Case study" ImageUrl="~/Assets/Design/buttons/btn-update.gif" CssClass="btn fltr" runat="server" OnClick="btnSave_OnClick" />
<div class="clearBoth"></div>
Shouldn't the RequiredFieldValidator be fired off when TryCreate fails on a dodgy URL and txtImgUrl.Text = ""?
Is there something blatantly obvious that I'm missing here?
Any help is much appreciated

You should check on button click
if (Page.IsValid)
{
lblOutput.Text = "Required field is filled!";
}
else
{
lblOutput.Text = "Required field is empty!";
}
In ASPX in the button add
CausesValidation="true"

Related

How to get asp:textbox contents for a function that's inside a <script> tag?

Here is the entire code I have for a simple login page done in ASP.NET:
<p></p>
User:
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<p></p>
Pass:
<asp:TextBox ID="TextBox2" runat="server" TextMode="Password"></asp:TextBox>
<p></p>
<asp:Label ID="Label1" runat="server" Text="" />
<div id="wrapper">
<button id="buttona" type="button">Sweet Alert!</button>
</div>
<script>
$('#buttona').click(function () {
if (('#TextBox1').valueOf == "user" && ('#TextBox2').valueOf == "pass") {
swal("Yay!", "You logged in succesfully", "success");
}
else {
swal("Oh noez", "That's incorrect", "error");
}
});
</script>
The goal is to show a positive message when the login is successful, and an error message when it's not (using SweetAlert).
My issue is that it's always showing the "Incorrect" message, and I assume what's wrong is that it's not reading the TextBox contents properly (the syntax doesn't look very correct to me but I'm not sure how it's supposed to be). I've tried replacing .valueOf with .text as well but it didn't help.
How can I get the contents (text) that get inputted in each asp:TextBox ?
You can get TextBox1 and TextBox2 values by
var textbox1 = document.getElementById('<%= TextBox1.ClientID %>').value;
var textbox2 = document.getElementById('<%= TextBox2.ClientID %>').value;

Creating Comment box With Reply Option using Asp.Net

I am tring to Create a Comment box having reply option for my Website
Below Is My aspx page
<div>
<asp:Repeater runat="server" ID="repAnswer">
<ItemTemplate>
<h6>Answer</h6>
<p><%# Eval("Answer") %></p>
<asp:Label runat="server" ID="lblAnsId" Text='<%# Eval("AnsId")%>' Visible="false"></asp:Label>
<a class="link" id='lnkReplyParent<%#Eval("AnsId") %>' href="javascript:void(0)" onclick="showReply(<%#Eval("AnsId") %>);return false;">Reply</a>
<a class="link" id="lnkCancle" href="javascript:void(0)" onclick="closeReply(<%#Eval("AnsId") %>);return false;">Cancle</a>
<div id='divReply<%#Eval("AnsId") %>' style="display:none;">
<asp:TextBox ID="textCommentReplyParent" CssClass="input-group" runat="server" Width="300px" TextMode="MultiLine" ></asp:TextBox>
<br />
<asp:Button ID="btnReplyParent" runat="server" Text="Reply" OnClick="btnReply_Click" /></div>
</ItemTemplate>
</asp:Repeater>
</div>
<div style="margin-top:100px">
<h5>Your Answer</h5>
<hr />
<CKEditor:CKEditorControl ID="txtAddAnswer" BasePath="Admin/ckeditor/" runat="server">
</CKEditor:CKEditorControl>
<asp:Button runat="server" ID="btnAnswer" Text="Submit Answer" OnClick="btnAnswer_Click"/>
</div>
i have used Repeater to bind my answer or comment. Inside the repeater i have given two link pne is of reply other is of cancel.when someone click on the reply a new textbox and button open which is used to give the reply
Below is my cs page
protected void btnReply_Click(object sender, EventArgs e)
{
foreach (RepeaterItem row in repAnswer.Items)
{
Label lblNewAnsIdholder = (Label)row.FindControl("lblNewAnsIdholder");
TextBox txtReplyToAnswer = (TextBox)row.FindControl("txtReplyToAnswer");
OnlineSubjects onlinesub = new OnlineSubjects()
{
reply = txtReplyToAnswer.Text.Trim(),
AnsId = Convert.ToInt32(lblNewAnsIdholder.Text.ToString())
};
onlinesub.addAnswer();
}
}
i dont know how to use textbox in repeater but after searching it through google i get something like this which i am not sure thats right or wrong.
And the line where i have created my object for my class i am getting error from there
I am tring to pass the value of textbox as a paramter
Plz help me to do this.
Thank You
You Should try,
TextBox txtReplyToAnswer = ((TextBox)row.FindControl("txtReplyToAnswer")).Text;
Hope this will work.

How to show pop up div from server side on button click

I am working on Payment page and i want to show a popup for showing message your payment is processing. so for now i am using CustomValidator and Submit Button. and i want to show this popup when Args is valid. my code is.
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="" OnServerValidate="CustomValidator1_ServerValidate"
EnableClientScript="true" ValidationGroup="Authorize"></asp:CustomValidator>
<asp:Button ID="SubmitButton" runat="server" Text="Pay now" CausesValidation="true" CssClass="blue paynow" style="width:200px;"
ValidationGroup="Authorize" OnClick="SubmitButton_Click" OnClientClick="validate(ContentPlaceHolder1_chk_agree);" />
One better approach is to go with "updateProgress".
Place your submit button inside a updatePanel and place a loading gif image inside updateProgress which will show below loading image when payment progress is going on and will close automatically when payment is complete.
Loading ....
<asp:UpdateProgress id="updateProgress" runat="server">
<ProgressTemplate>
<asp:Image ID="imgUpdateProgress" runat="server" ImageUrl="~/images/loadingNew.gif" AlternateText="Loading ..." ToolTip="Loading ..."/>
</ProgressTemplate>
</asp:UpdateProgress>
To show a message box after validation, you can do the following:
Add the following javascript to your <head>
<script language="javascript">
function SubmitButton_ClientClick()
{
bool isValid = Page_ClientValidate("Authorize"); //triggers validation
if (isValid)
{
alert('Your payment is processing');
}
return isValid;
}
</script>
Then, change your button like this:
<asp:Button ID="SubmitButton" runat="server" Text="Pay now" CausesValidation="true"
CssClass="blue paynow" style="width:200px;"
ValidationGroup="Authorize" OnClick="SubmitButton_Click"
OnClientClick="return SubmitButton_ClientClick();" />
An even better approach is to use a popup div - here is a very basic example:
Add this somewhere in your <body>
<div id="popup_box" style="height:300;width:300;position:absolute;top:150;left:350;border:3px solid red;background:#d8d8d8;display:none;">
<h1>Payment is processing</h1>
<button id="popupBoxClose" onclick="document.getElementById("popup_box").style.display = 'none';">Close</button>
</div>
And modify the SubmitButton_ClientClick like this:
function SubmitButton_ClientClick()
{
bool isValid = Page_ClientValidate("Authorize"); //triggers validation
if (isValid)
{
document.getElementById("popup_box").style.display = '';
}
return isValid;
}

CustomValidator OnServerValidate Not Working

I am trying to utilize a CustomValidator using the keyword "OnServerValidate"
Here is where I have it setup in my .aspx file:
<div class="label">
<div><label for="parentemail1">Email Address</label></div>
<div><asp:TextBox ID="parentemail1" runat="server" MaxLength="40" Columns="40"></asp:TextBox></div>
<asp:CustomValidator id="ParentEmail1Required"
ControlToValidate="parentemail1"
Display="Dynamic"
ErrorMessage="Required"
ValidateEmptyText="true"
OnServerValidate="ServerValidator"
runat="server"/>
</div>
and here is the C# code behind method for OnServerValidate:
protected void ServerValidator(object source, ServerValidateEventArgs args)
{
args.IsValid = false;
}
Am I missing something, shouldn't the CustomValidator fire when the form is submitted?
I've read through a bunch of posts and even tried this with a RequiredFieldValidator on the same control but no luck. I have this working with ClientValidationFunction but I want to access the properties in the code behind instead of the DOM.
Any help would be greatly appreciated.
Try this
protected void ServerValidator(object source, ServerValidateEventArgs args)
{
if(args.IsValid == false)
return;
Response.Redirect("NextPage.aspx");// It will not fire if page is not valid.
}
Well, the argument args is not sent to server and that's why you don't get server message. Add a button can do this.
Change the code to
<div>
<div class="label">
<div><label for="parentemail1">Email Address</label></div>
<div><asp:TextBox ID="parentemail1" runat="server" MaxLength="40" Columns="40"></asp:TextBox>
<br />
<asp:Button ID="btnSendData" runat="server" Text="Send Data" />
</div>
<asp:CustomValidator id="ParentEmail1Required"
ControlToValidate="parentemail1"
Display="Dynamic"
ErrorMessage="Required"
ValidateEmptyText="true"
OnServerValidate="ServerValidator"
runat="server" SetFocusOnError="True"/>
</div>
</div>

asp.net c# validation

I am trying to create a simple form that uses radio buttons. I set the radio button to AutoPostBack = True, this way if the radio button is true/false, a subpanel is Shown or Hidden. The radio buttons are required fields. I also have a hidden textbox that the value of the selected radio button is inserted and this textbox is what I validate against (empty or not).
Problem 1:
This works until you go to submit and the validation fails. The validation messages show, then when you click on one of the radio buttons with AutoPostBack = True, all the validation disappear. I can resolve this by adding Page.Validate() to the method that runs when the radio button is clicked. But, I do not want the Page.Validate() to run unless the page was already showing validation errors (so it will not re-validate unless the form was already submitted and failed the validation).
As it stands, before the form is submitted and fails validation: when you click on any radio button question, all the other questions requiring validation show the validation error. I am only looking to overcome the AutoPostBack which is clearing all the validation messages that are shown when you had click submit.
Problem 2:
I would like to be able to change the color of the question if it does not pass validation. I added the javascript to override the default .net settings. I got this to work, but only when you click the submit button and not after a RadioButton AutoPostBack.
Currently, When you click submit all the required questions turn red and also display the required validation message. But if you click a radio button to start fixing the validation errors, on the AutoPostBack, the all the questions that were now red in color changes back to the orignal black and the required validation message is still shown. How can I call the Javascript to run again along with the Page.Validation() in the code behind method?
Any help would be greatly appricated! Thanks
Below is an example of the code so far.
ASPX Code:
<asp:Table ID="Table1" runat="server" CellSpacing="0" CellPadding="0">
<asp:TableRow>
<asp:TableCell CssClass="question">
<label>4. Have you had an abnormal result from a prenatal test (e.g. amniocentesis, blood test, ultrasound)?</label>
</asp:TableCell>
<asp:TableCell CssClass="answer">
<ul class="selectGroup">
<li>
<asp:RadioButton ID="Q4_true" runat="server" Checked='<%# Bind("Q4_yes") %>' Text="Yes"
GroupName="4" OnCheckedChanged='RB_QuestionSubPane_YN' AutoPostBack="true" /></li>
<li>
<asp:RadioButton ID="Q4_false" runat="server" Checked='<%# Bind("Q4_no") %>' Text="No"
GroupName="4" OnCheckedChanged='RB_QuestionSubPane_YN' AutoPostBack="true" />
</li>
<asp:TextBox ID="Q4_validationBox" runat="server" CssClass="hiddenField" Enabled="false"
Text=''></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" EnableViewState="true" ControlToValidate="Q4_validationBox"
Display="Dynamic" runat="server" ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator>
</ul>
</asp:TableCell>
</asp:TableRow>
</asp:Table>
Code Behind
protected void RB_QuestionSubPane_YN(object sender, EventArgs e)
{
RadioButton radio_Selected = (RadioButton)sender;
string radio_QuestionID = Convert.ToString(radio_Selected.ID);
(((TextBox)FormView1.FindControl(strQuestionID + "_validationBox")).Text) = radio_Selected.ID.ToString();
Page.Validate();
}
JavaScript
ValidatorUpdateDisplay = function (val) {
var ctl = $('#' + val.controltovalidate);
var eCount = 0;
for (var i = 0; i < Page_Validators.length; i++) {
var v = Page_Validators[i];
if (v.controltovalidate == val.controltovalidate) {
if (!v.isvalid) {
eCount++;
ctl.addClass('validationError');
$('td.question:eq(' + i + ')').addClass('red');
}
};
}
if (eCount > 0) {
ctl.addClass('validationError');
} else {
ctl.removeClass('validationError');
$('td.question:eq(' + i + ')').removeClass('red');
}
if (typeof (val.display) == "string") {
if (val.display == "None") {
return;
}
if (val.display == "Dynamic") {
val.style.display = val.isvalid ? "none" : "inline";
return;
}
}
if ((navigator.userAgent.indexOf("Mac") > -1) &&
(navigator.userAgent.indexOf("MSIE") > -1)) {
val.style.display = "inline";
}
val.style.visibility = val.isvalid ? "hidden" : "visible";
}
It sounds like what you really need is custom validation. That way you can fully customize your validation to meet your needs.
Here is a simple example:
<script language="javascript" type="text/javascript" >
function CustomValidator1_ClientValidate(source,args)
{
//put your javascript logic here
}
//-->
</script>
<body>
<form id="form1" runat="server">
<div>
<asp:RadioButton ID="RadioButton1" runat="server" GroupName="direction" Text="left" />
<asp:RadioButton ID="RadioButton2" runat="server" GroupName="direction" Text="right" />
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
<asp:CustomValidator id="CustomValidator1" runat="server" Display="Dynamic" ErrorMessage="please choose" ClientValidationFunction="CustomValidator1_ClientValidate" OnServerValidate="CustomValidator1_ServerValidate"></asp:CustomValidator>
</div>
</form>
</body>
Server Side
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
args.IsValid = RadioButton1.Checked || RadioButton2.Checked;
}
protected void Button1_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
//validate is successful.
}
}

Categories

Resources