How to display Validation Message from code behind - c#

I have one textbox..
i want to validate it's value based on dropdownlist value..
So i am displaying message from code behind using RegularExpressionValidator..
But it is not working plz,give me suggestion..
<asp:TextBox ID="tbnooflecture" runat="server" Width="119px" Height="33px"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" ForeColor="#6600FF"
runat="server" ValidationGroup="upper"
ControlToValidate="tbnooflecture"></asp:RegularExpressionValidator>
<asp:Button ID="bfillattendence" runat="server" Text="To Fill Attendence Click Here"
onclick="FillAttendence_Click" Width="218px" Height="33px" CausesValidation="true" ValidationGroup="upper"/>
i am writing below code in Button click event
string batchname = dpbatchname.SelectedItem.Text.ToString();
int lengthofbatch=batchname.Length;
if(lengthofbatch==2)
{
RegularExpressionValidator1.ValidationExpression = "[1-9][02468]|[02468]";
RegularExpressionValidator1.ErrorMessage = "Only Even No. of Attendence is Valid for Lab.";
}
else if (lengthofbatch == 1)
{
RegularExpressionValidator1.ValidationExpression = "[0-9][0-9]|[0-9]";
RegularExpressionValidator1.ErrorMessage = "Attendence Shold be Like 9,50";
}
else
{
RegularExpressionValidator1.ValidationExpression = "[0-9][0-9]|[0-9]";
RegularExpressionValidator1.ErrorMessage = "Attendence Shold be Like 9,50";
}

Are you validating Textbox value?
If you use regular expression on server side, then you need to validate input (your textbox) like
below, and display message.
if (Regex.IsMatch(text, reg))
{
}

Add this line
RequiredFieldValidator1.IsValid = false;
after
RegularExpressionValidator1.ValidationExpression = "[0-9][0-9]|[0-9]";
RegularExpressionValidator1.ErrorMessage = "Attendence Shold be Like 9,50";

Related

ASP.NET server side validation not firing

In My Application server side validation function is not working.even function is not called. i have put debugger on thuat function but it is not stopped ny debugger .i.e. function is not called
<asp:TextBox type="text" ID="txtMobilePhone" runat="server" ClientIDMode="Static" CausesValidation="true"/>
<asp:CustomValidator ID="cvMobilePhone" runat="server" OnServerValidate="cvMobilePhone_ServerValidate"
Text="Mobile Phone already exist in this Reward Program." ErrorMessage="Mobile Phone already exist in this Reward Program."
Display="Dynamic" ValidationGroup="vgStep2" ControlToValidate="txtMobilePhone" CssClass="error"></asp:CustomValidator>
<asp:RequiredFieldValidator ID="rfvMobilePhone" runat="server" ControlToValidate="txtMobilePhone"
ErrorMessage="Mobile Phone is required." CssClass="error" ValidationGroup="vgStep2"></asp:RequiredFieldValidator>
<asp:CustomValidator ID="cvMobilePerVal" runat="server" ClientValidationFunction="validateEmailOrMobilePerVal"
Display="Dynamic" ValidationGroup="vgStep2"></asp:CustomValidator>
<asp:Button ID="btnStep2Upper" runat="server" ClientIDMode="Static" OnClick="btnSaveContactClick" Text="Save" ValidationGroup="vgStep2" vg="vgStep2" OnClientClick="return ClientValidate();" />
Server Side Code
protected void cvMobilePhone_ServerValidate(object source, ServerValidateEventArgs value)
{ /* I have put debugger here but control is not coming here*/
/* my validation logic*/
protected void cvMobilePhone_ServerValidate(object source, ServerValidateEventArgs value)
{
if (txtMobilePhone.Text.Trim() != "")
{
RewardProgramDataContext db = new RewardProgramDataContext();
Boolean f = false;
string MobilePhone = cmnFunc.RemoveMobilePhoneFormat(txtMobilePhone.Text.Trim());
if (Request["id"] != null)
{
var cData = db.spContactSelectAllSingle(new Guid(Request["id"])).SingleOrDefault();
if (cData != null)
{
if (cmnFunc.RemoveMobilePhoneFormat(cData.MobilePhone) == MobilePhone)
{
f = true;
value.IsValid = true;
}
}
}
if (f == false)
{
var res = db.spContactDuplicateMobile(new Guid(ddlContactList.SelectedValue), MobilePhone).SingleOrDefault();
if (res.Column1 <= 0)
{
value.IsValid = true;
customIsValid = true;
}
else
{
value.IsValid = false;
customIsValid = false;
}
}
}
}
now when i click submit button all clent side validation working but serside custom validator is not calling
You forget to set the ControlToValidate property?
<asp:CustomValidator ID="cvMobilePhone" runat="server" ControlToValidate="txtMobilePhone" OnServerValidate="cvMobilePhone_ServerValidate"
Text="Mobile Phone already exist in this Reward Program." ErrorMessage="Mobile Phone already exist in this Reward Program."
Display="Dynamic" ValidationGroup="vgStep2" CssClass="error"></asp:CustomValidator>
You have a combination of two different things causing this behaviour.
Firstly, note that although—as has been said by others—you do not have to specify ControlToValidate, doing so restricts the circumstances in which the server-side custom validation event will fire. Specifically, if you leave it unset, the event always fires on postback, whereas if you set it, the event only fires when the control identified by ControlToValidate has a non-empty value.
Secondly, by specifying OnClientClick, you are telling the framework that you will take care of client-side validation, which will now not fire unless you call it from your OnClientClick function. Although you have not included your ClientValidate function in your question, I suspect you are not doing so, which leaves your RequiredFieldValidator powerless to prevent the postback.
In combination, these two things mean that
the postback occurs despite the empty textbox, and
the server-side custom validation does not fire on postback, because of the empty textbox.
You can call the client validation from your custom function using Page_ClientValidate()), which will be present in your page script since the page contains validators.
function ClientValidate() {
if (Page_ClientValidate()) {
//do custom validation, maybe return false
return true;
}
else {
return false;
}
}

Confirm dialog with ok/cancel

I am using a WebForms GridView control. When a user clicks "Update" on a row, I want to check the values they entered against some other records.
From that, if I return true, I'd like to display a confirm dialog asking the user if they'd like to continue with their update.
A javascript confirm dialog probably won't work because I don't always want to show this dialog, only when the values entered meet a certain condition.
Any suggestions?
I would suggest using the RowDataBound event to check for those conditions and add the confirmation dialog where needed.
EDIT : Compare dates and show a confirmation if they're different
See this jsFiddle for a demonstration.
<script type="text/javascript">
validateInput = function(inputDate, compareDate, confirmButtonID) {
var confirmButton = document.getElementById(confirmButtonID);
if (confirmButton) {
$(confirmButton).one("click", function() {
var result = dates.compare(inputDate, compareDate);
if (result != 0){ //change to suit your needs
return confirm("Are you sure you want to save these changes?");
}
return true;
});
}
}
</script>
And here's the code for the dates class used for the comparison (link):
<script type="text/javascript">
var dates = {
convert:function(d) {
return (
d.constructor === Date ? d :
d.constructor === Array ? new Date(d[0],d[1],d[2]) :
d.constructor === Number ? new Date(d) :
d.constructor === String ? new Date(d) :
typeof d === "object" ? new Date(d.year,d.month,d.date) :
NaN
);
},
compare:function(a,b) {
return (
isFinite(a=this.convert(a).valueOf()) &&
isFinite(b=this.convert(b).valueOf()) ?
(a>b)-(a<b) :
NaN
);
},
inRange:function(d,start,end) {
return (
isFinite(d=this.convert(d).valueOf()) &&
isFinite(start=this.convert(start).valueOf()) &&
isFinite(end=this.convert(end).valueOf()) ?
start <= d && d <= end :
NaN
);
}
}
</script>
In the RowDataBound event of the GridView, assign the onchange function for each row:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
var inputCtrl = e.Row.FindControl("txtEnteredDate") as TextBox;
if (inputCtrl != null)
{
var updateButtonCtrl = e.Row.FindControl("btnUpdate") as Button;
if (updateButtonCtrl != null)
{
inputCtrl.Attributes["onchange"] = string.Format("return validateInput(this.value, '{0}', '{1}');", DataBinder.Eval("DateToCompare"), updateButtonCtrl.ClientID);
}
}
}
jQuery Confirmation Dialog
If you need something more flexible than a regular JavaScript confirm dialog, you can change the above to use the jQuery UI Dialog as a confirmation instead.
If you are using WebForms (?), you need to add some validation controls to the GridView template.
Here is an example from MSDN using a CompareValidator:
<EditItemTemplate>
<asp:TextBox ID="EditUnitPrice" runat="server"
Text='<%# Bind("UnitPrice", "{0:c}") %>'
Columns="6"></asp:TextBox>
<asp:CompareValidator ID="CompareValidator1" runat="server"
ControlToValidate="EditUnitPrice"
ErrorMessage="The price must be greater than or equal to zero and
cannot include the currency symbol"
Operator="GreaterThanEqual" Type="Currency"
ValueToCompare="0">*</asp:CompareValidator>
</EditItemTemplate>

Making a validator work from the back end code

I added a regex validator but its not showing anything on the page, basically the validation is done somewhere else i just needed to fire up. Here is the validator
<div>
<asp:RequiredFieldValidator
ID="RegularNoCardAccepted" runat="server"
ControlToValidate="txtCreditCardNumber"
CssClass="Error" Display="Dynamic">
</asp:RequiredFieldValidator>
</div>
And here is how I am trying to fire up, in reality i dont need it to check against a regular expression, I am just not sure how to make it pop up when it meets this condition
if (CardNotAccepted())
{
//Find the validator located somewhere in the master page.
RequiredFieldValidator reqVal =
FindControlRecursive(this.Page.Master, "RegularNoCardAccepted")
as RequiredFieldValidator;
if (reqVal != null)
{
//The code goes through here but it never shows.
reqVal.Enabled = true;
reqVal.Text = "Credit Card Type is not accepted";
reqVal.Visible = true;
reqVal.Validate();
}
return;
}
ASP.NET FieldValidators work automatically (assuming the Enabled property is set to true) on POST events. Here is an example of use: http://www.w3schools.com/aspnet/showasp.asp?filename=demo_reqfieldvalidator

How I turn label in asp red

Hi I would like to turn label red in .aspx when user enters wrong answer into textbox.
but not know how, hw I can do this?
You can do this using javascript (call this code from onchange of the textbox):
<label for="myTextBox" id="myLabel">For my textbox</label>
<input id="myTextBox" onchange="ValidateAnswer();">
function ValidateAnswer() {
var txtBox = document.getElementById('myTextBox');
if(txtBox.value != "answer") {
document.getElementById('myLabel').style.color = 'red';
}
}
You can also use the Validator controls if you're using ASP.Net:
<asp:CustomValidator runat="server" ID="cvAnswer"
ControlToValidate="myTextBox"
ErrorMessage="required"
ClientValidationFunction="ValidateAnswer"
ValidateEmptyText="true"
Display="Dynamic"
ValidationGroup="First"
ForeColor="red" >
</asp:CustomValidator>
function ValidateAnswer(sender, args) {
args.IsValid = args.Value != "" && args.Value == "answer here";
if(!args.IsValid) {
document.getElementById('myLabel').style.color = 'red';
}
return;
}
From the server side code:
if(this.txtBox.Text.Length == 0)
{
//no value entered
lblMyLabel.BackColor = Color.Red;
lblMyLabel.Text = "Invalid entry";
}
Client side you can do this:
Markup:
<asp:TextBox onchange="Validate();" runat="server" id="myTextBox"/>
JS:
function Validate()
{
var t = document.getElementByID("myTextBox");
var l = document.getElementByID("myLabel");
if (t.Length == 0)
{
l.style.backgroundColor='red';
}
}
There are multiple options, some server side, and some client side, but in both cases it involves validation. Essentially you are looking to change a css class or other style property on the label.
C# code behind:
if(yourConditionText != "YourExpectedValue")
{
youTextBox.BackColor = System.Drawing.Color.Red;
}
In the Server side button click event (which will be automatically generated when you double click on the button in Design view of the aspx page):
protected void Button_Click(...)
{
if(txtYourTextBox.Text != "YourDesiredValue")
{
lblYourLabel.ForeColor = Color.Red;
}
}
Better still, you could use String.Compare (recommended) as below:
if(string.Compare(txtYourTextBox.Text, "YourDesiredValue") != 0) //0 = Match
{
lblYourLabel.ForeColor = Color.Red; //For backColor set BackColor property
}
Hope it helps!

Customer Validation ASP.Net C#

I am having the same problem as someone else in this forum. My validation control is not firing...and not sure where I have gone wrong. Could someone please take a look and let me know what obvious error I have here...thanks
I have set up a customer validator in my aspx page using the following:
<asp:TextBox ID="EmployeeNumber2TextBox" runat="server"
Text='<%# Bind("EmployeeNumber") %>'Visible='<%# AllowEmployeeNumberEdit() %>' />
<asp:CustomValidator ID="ValidateEmpNumber" runat="server"
onservervalidate="ValidateEmpNumber_ServerValidate"
controltovalidate="EmployeeNumber2TextBox"
ErrorMessage="You Must Enter an Employee Number" Text="*" />
and the code behind:
protected void ValidateEmpNumber_ServerValidate(object sender, System.Web.UI.WebControls.ServerValidateEventArgs e)
{
int SiteCompanyID = System.Convert.ToInt32(Session["SiteCompanyID"]);
SiteCompanyBLL SiteCompany = new SiteCompanyBLL();
SiteCompanyDAL.SiteCompanyRow ScRow = SiteCompany.GetCompanyByID(SiteCompanyID);
bool AutoGenerate = ScRow.AutoGenNumber; // result returning true or false
if (AutoGenerate == false)
{
if (e.Value.Length == 0)
e.IsValid = false;
else
e.IsValid = false;
}
}
Is the validator in sync with the control that is doing the submit/postback? Also, there is no condition that allows it to be true.
How do you know it isn't firing?
Did you try making the OnServerValidate and ControlToValidate with the first letter of each word uppercase? Those properties may be case sensitive.
I was able to run a cutdown version of your code on my system.
Are you sure your Web.config is set to compile debug?:
<compilation debug="true">

Categories