asp:CustomValidator - user input is equal to a set parameter - asp.net

I am not too familiar with custom validation. If you are willing to help, it is MUCH appreciated!
<asp:CustomValidator ID="valMatchUserInput" runat="server" ControlToValidate="tbUserInput" ErrorMessage="Please do something."> </asp:CustomValidator>
Basically, if the user input does not match (is not equal to) a specific parameter, I would like an error message to display, so nothing happens until the user fixes the error.
Thanks!

I will give you an example...
Let's say this is your validator:
<asp:CustomValidator ID="valMatchUserInput" runat="server" ControlToValidate="tbUserInput" ErrorMessage="Please do something." **ClientValidationFunction="Bla_ClientValidate" OnServerValidate="Bla_ServerValidate"**> </asp:CustomValidator>
You have to include a server-side validation and a client-side validation.
Code behind (server-side)
protected void Bla_ServerValidate(object source, ServerValidateEventArgs args)
{
//Compare your parameter here
}
Javascript (client-side)
function bla_ClientValidate(sender, e) {
// Compare your parameter here
}
It should work then

Related

Showing single error for multiple asp validators

I have a text box control in asp with 3 different validators. Each validator is getting its error message from the server, and each one validates different things.
My problem is that for some values, two or more validators are firing and I'm getting more then one error message.
I would like to make some kind of priority functionality, meaning that if the first validator is firing the other two will not. Is there any way to make the validator behave like that?
I've added some code sample:
<asp:RequiredFieldValidator ID="cvRequired" runat="server" Display="Dynamic"
ControlToValidate="txtBox" />
<asp:RegularExpressionValidator ID="cvFormat" runat="server" Display="Dynamic"
ControlToValidate="txtBox" ValidationExpression="^([A-Za-z])+$" />
<asp:CustomValidator ID="cvCustom" runat="server" Display="Dynamic"
ControlToValidate="txtBox" ClientValidationFunction="validateFunction" />
I want that the format validator and the custom validator will not fire if the required validator is invalid (actually, I just want them to not showing their error message).
As I said, the error messages are from the server, so I can't really join them to one custom validator. Also, the "validateFunction" is in another js file (for re-use).
Few logic options you got to think about,
(txtPhone) having three validators.
1.RangeValidator, 2.CustomValidator 3.Regexvalidator
Say,after validation (check what it returns if validation fails/passes) and act upon that.
if(rangevalidator1 != null)
{
...somecode...
}
I ll suggest you using javascript ..
you can use a single custom validator for all three validation and you put your code in if condition according to your need.
<asp:CustomValidator runat="server" ID="cstmStartDateValidater"
ToolTip="Start date cannot be greater than equal to end date/time or less than current date/time"
ErrorMessage="*" ControlToValidate="txtStartDateTime"
ForeColor="Red" ValidationGroup="vlgMessage" SetFocusOnError="true"
onservervalidate="cstmStartDateValidater_ServerValidate" ></asp:CustomValidator>
in the .cs page
protected void cstmStartDateValidater_ServerValidate(object source, ServerValidateEventArgs args)
{
if (CompareStartDate())
{
args.IsValid = true;
}
else
{
args.IsValid = false;
}
}
you can use following link for more information :
MSDN,
Code Project
hope these will help you .
Make use of ValidatorCalloutExtender control which is available in ajax control toolkit.
Place a separate ValidatorCalloutExtender across each control,you wish to validate it.

How can I stop refreshing the page in the else condition

My code:
protected void btnOk_Click(object sender, EventArgs e)
{
if (txtReportFavorite.Text != string.Empty)
{
//..
}
else
{
Response.Write("<script>alert('Enter Favorite name.')</script>");
// I need to prevent page refresh here.
}
}
How can I stop refreshing the page in the else condition. Thanks.
You can't.
The new page has already been requested when that code runs. If you don't do a postback, that code will never run.
If you want to do the validation without doing the postback, you should do it using client code instead.
The fact that you got to the server side means that your page has done a full cycle to the server and refreshed itself.
Unless you are calling this code with an Ajax call.
You can also achieve this by placing an AjaxUpdatePanel around your button that will simulate an Ajax call when your clients will submit your form.
in your code behind on page load put this
btnOk.Attributes.Add("onclick","return validate();");
in your aspx file have this script
function validate()
{
if(document.getElementById("txtReportFavorite").value == "";
{
alert("Enter Favorite name");
return false;
}
}
Your page is already go to the server side and it is in already postback is progressing.
you have to use client side code for preventing postback.
why not to use RequiredFieldValidator if only empty textbox need to validate?
you can do it on client side.
<asp:TextBox runat="server" id="txtReportFavorite" />
<asp:RequiredFieldValidator runat="server" id="txtReportFavorite" controltovalidate="txtName" errormessage="Enter Favorite name!" />
<br />
<asp:Button runat="server" id="btnSubmit" text="Ok" onclick="btn_Click" />
protected void btnSubmitForm_Click(object sender, EventArgs e)
{
if(Page.IsValid) //for secure validation
{
//do something
}
}
Try using RegisterScriptBlock.
ClientScript.RegisterStartupScript(this.GetType),"","$(document).ready(function(){alert('Enter Favorite name.')});",true);
If you want to perform from server-side do it like above.. Otherwise many answers already posted.
The kind of functionality you are showing can be easily achieved by using a Validator so the page won't post back.
As once it reaches the server, its really not possible to stop the refresh. Well, at least as far as I know.
-Milind

Using CustomValidator control

We know usually the CustomValidator control will check the user's input against some arithmetic validation.
I have a textbox in my web form. The text of it doesn't come from user's input, it comes from the database.
MembershipUser user = Membership.Providers["SqlMembershipProvider"].GetUser(userName);
TextUserName.Text = AntiXss.HtmlEncode(user.UserName);
My goal is to use some kind of validator to check whether it is appropriate. If not then change it in the textbox and validate it again.
How to do it?
Thanks.
UPDATE CODE:
protected void ValidateUser()
{
string UserNameCreated = TextUserName.Text;
Match match = Regex.Match(UserNameCreated, #"^[a-zA-Z0-9]{6,}$",
RegexOptions.IgnoreCase);
}
<td class="style4">
<asp:TextBox ID="TextUserName" runat="server"></asp:TextBox>
</td><td><asp:CustomValidator ID="CustomValidatorUser" runat="server" ControlToValidate="TextUserName"
ErrorMessage="Minimum of 6 (six) alphanumeric characters."
OnServerValidate="ValidateUser" Display="Dynamic"
ValidateEmptyText="True" ></asp:CustomValidator></td>
Your ServerValidate has the wrong signature.
void ServerValidation(object source, ServerValidateEventArgs args)
{
args.IsValid = Regex.Match(TextUserName.Text, #"^[a-zA-Z0-9]{6,}$", RegexOptions.IgnoreCase);
}

server side validation in asp.net?

hi all as i know that asp.net provide server side validation control which has there own built-in logic, so i want to ask here can we extend built-in logic, i means suppose we use compare validator for comparing two file at this point it will validate according to there built-in logic, but i want to add some code for compare validator, is this possible.
According to my knowledge in asp.net every control treated as class which has data and code so according to inheritance or extend can we add some code in validation control ?
It looks like you need to use
CustomValidator
You can use a custom function to define when your control passes your validation. In this case could be something like this.
void ServerValidation (object source, ServerValidateEventArgs args)
{
args.IsValid = //Define your validation here
}
CustomValidator is one option. If you rather going to implement validator similar to existing one, you can simply derive from it and override all necessary methods. But the most important method you should look for is the EvaluateIsValid.
A CustomValidator is better in situations when your logic is more likely unique. In case you want to use the logic in multiple places, I would recommend to use inheritance. It allows you to encapsulate the logic in class library if you want, CustomValidator doesn't.
In your markup:
<asp:TextBox id="Text1" runat="server" />
<asp:CustomValidator id="CustomValidator1"
ControlToValidate="Text1"
Display="Static"
ErrorMessage="Not an even number!"
ForeColor="green"
Font-Names="verdana"
Font-Size="10pt"
OnServerValidate="ServerValidation"
runat="server"/>
<asp:Button id="Button1"
Text="Validate"
OnClick="ValidateBtn_OnClick"
runat="server"/>
In the server side code:
void ValidateBtn_OnClick(object sender, EventArgs e)
{
// Display whether the page passed validation.
if (Page.IsValid)
{
Message.Text = "Page is valid.";
}
else
{
Message.Text = "Page is not valid!";
}
}
void ServerValidation(object source, ServerValidateEventArgs args)
{
try
{
// Test whether the value entered into the text box is even.
int i = int.Parse(args.Value);
args.IsValid = ((i%2) == 0);
}
catch(Exception ex)
{
args.IsValid = false;
}
}
This example is a shortened version of the one found at the documentation page for CustomValidator:
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.customvalidator.aspx
Yes you can. Like Carlos's answer link will tell you. You can put the code in the code behind.(.cs file)

What determines the order validators fire in?

I have a webform with two custom validators:
One to validate that a string is a date. I don’t care what format, so long as it’s parseable.
Another to ensure that one date is equal to or greater than another. I just couldn’t get the compare validator to play nice with any date format.
<asp:TextBox ID="txtResourceStartDate" runat="server"
CssClass="textBox mandatory dateField" />
<asp:CustomValidator ID="valResourceStartDateIsDate" runat="server"
ControlToValidate="txtResourceStartDate" Display="None"
ErrorMessage="Start date must be a valid date"
OnServerValidate="Date_ServerValidate" />
<asp:TextBox ID="txtResourceEndDate" runat="server"
CssClass="textBox mandatory dateField" />
<asp:CustomValidator ID="valResourceEndDateIsDate" runat="server"
ControlToValidate="txtResourceEndDate" Display="None"
ErrorMessage="End date must be a valid date"
OnServerValidate="Date_ServerValidate" />
<asp:CustomValidator Display="None" Text="" ID="valForStartEndDate" runat="server"
OnServerValidate="ValidateStartEndDate"
ErrorMessage="Last day must be greater than or equal to first day" />
protected void Date_ServerValidate(object source, ServerValidateEventArgs args)
{
DateTime outDate;
args.IsValid = DateTime.TryParse(args.Value, out outDate);
}
protected void ValidateStartEndDate(object sender, ServerValidateEventArgs e)
{
e.IsValid = DateTime.Parse(txtResourceEndDate.Text) >=
DateTime.Parse(txtResourceStartDate.Text);
}
The problem is that the ValidateStartEndDate validator is firing before the Date_ServerValidate validator, so if the date is not valid, a format exception is thrown on DateTime.Parse. Obviously this validator could check for a valid date before parsing, but I’d really prefer to have a discrete validator with an appropriate message.
So the question is this: what determines the sequence with which the validators fire? Unless I’m missing something, this is not declared at the tag level.
You can't count on a certain sequence the validators will fire and also you shouldnt. You have to make sure for yourself that the order is irrelevant.
So you could
check for the valid date
simultaneously with the
Equal-Greater-Check.
First Call your IsDate-Validator's Validate()-Function and then check if it IsValid
All validators are added to the Page.Validators collection and validation runs through this collection in order. If your logic really should rely on this order: change the order of the validators in the ASPX-Page
Some interesting infos about Page-Validation: http://msdn.microsoft.com/en-us/library/aa479045.aspx
Validation control execution order is determined by the order of the controls in the ValidatorCollection returned by Page.Validators. This order is, in turn, determined by the order of the validation controls in the markup, with some exceptions (e.g. validators within data-bound controls will get added to the collection later, and so will be at the end).
If you set CausesValidation=false on your button and then trigger validation manually with Page.Validate, you can use the Add and Remove methods on the ValidatorCollection to change the execution order:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack) {
// move myValidator to the very end, so it executes last
Validators.Remove(myValidator);
Validators.Add(myValidator);
}
}
Then, later on in the triggering control:
protected void myButton_Click(object sender, EventArgs e)
{
Page.Validate();
if (!Page.IsValid) { return; }
// validation passed, proceed...
}
Disclaimer: all of this is empirical, I haven't found MSDN docs to back it up, but it seems to work.

Resources