Server-side validation in ASP.NET 2.0 - asp.net

My application is in ASP.NET 2.0 with C#. I have a regular expression validator with the regular expression ^[0-9]*(\\,)?[0-9]?[0-9]?$, now my client don't want this validation at client side but on button click i.e. Server Side.
EX: I have to check the value of txtPrice textbox
Please let me know how can I put this regular expression validation on server side.
Thanks in advance.

You can use a CustomValidator which can link to a server side event:
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="CustomValidator" OnServerValidate="CustomValidator1_Validate"></asp:CustomValidator>
Then server side you can validate input
protected void CustomValidator1_Validate (object source, ServerValidateEventArgs argss)
{}
Remember to wrap your submit button click with
if(IsValid) {}
To ensure all validators are respected

The control will validate on the server side always, regardless of whether you also enable client-side validation. But you must then remember to check the value of Page.IsValid before accepting the postback...
As has already been said, you can turn off client-side validation with an attribute.

Try to add EnableClientScript="false" to the validator.

Client-side validation using server-side controls based on ValidatorBase takes place only on PostBack i.e. on any server-side button/linkbutton click.
So you can use RegularExpressionValidator:
<asp:TextBox runat="server" ID="txtPrice" />
<asp:RegularExpressionValidator runat="server" ControlToValidate="txtPrice" ValidationExpression="^[0-9]*(\\,)?[0-9]?[0-9]?$" ErrorMessage="Input is incorrect" />
Also you can use CustomValidator:
<asp:TextBox runat="server" ID="txtPrice" />
<asp:CustomValidator runat="server" ControlToValidate="txtPrice" ErrorMessage="Input is incorrect" OnServerValidate="CustomValidator1_ServerValidate" />
protected void CustomValidator1_ServerValidate(object sender, ServerValidateEventArgs e)
{
// use e.Value to validate and set e.IsValid
// it's different depending on control to validate.
// for custom controls you can set it using ValidationPropertyAttribute
}

Related

UserControl conditional validation approach?

I have a custom UserControl which contains several TextBoxes with Validators. One TextBox with corresponding Validator is optional based on a CheckBox. Pseudo:
My Control.ascx:
<asp:TextBox id="txtAddress" />
<asp:Validator id="valAddress" />
<asp:CheckBox id="condition" />
<asp:TextBox id="txtConditional" />
<asp:Validator id="valConditional" ValidationGroup="ConditionalGroup" />
My Control.ascx.cs
public void Validate() {
if(condition.Checked) {
Page.Validate("ConditionalGroup");
}
}
I also have a page which basically looks like this:
Page.aspx
<my:Control id="myControl" />
<asp:Button onClick="doPost" />
Page.aspx.cs
protected void doPost(object sender, EventArgs e) {
myControl.Validate(); //This feels wrong
if(Page.IsValid) {
//go
}
}
This all works, however I would like to take the myControl.Validate() line out of the Page.aspx.cs and put it in the My Control.ascx.cs. Putting it in the Page_Load of the control is not an option because the conditional checkbox value is always false. There is no event available after Page_Load and before the doPost click handler is fired...
It feels wrong to call the custom Validate function on the Page where I think it should belong somewhere in the UserControl. Is it true that this is architecturally wrong? Is there another solution for this maybe by using an event handler?
You could try by enabling the validator only if the user checks on the check box. And disable the validator if the unchecks it. This has to be done in the user control. It can be done in the client side or in the server side. In this way, the page would validate all the validators that are enabled for the page.

No error message displayed for custom validator

I have a requirement that one of multiple fields is required. Using custom validator the even fires, false is returned, but no error message is display and the form validates.
What am I missing? I have tried with and without ValidationSummary.
Thanks!
<asp:CustomValidator ID="CustomValidator1" OnServerValidate="validatePhone" EnableClientScript="false" runat="server" ErrorMessage="Home or Cell Phone is Required" ></asp:CustomValidator>
<asp:ValidationSummary ID="ValidationSummary1" DisplayMode="BulletList" runat="server" ForeColor="Red" Font-Size="X-Small" Font-Bold="true" />
protected void validatePhone(object sender, ServerValidateEventArgs e)
{
e.IsValid = string.IsNullOrEmpty(txtCellPhone.Text) && string.IsNullOrEmpty(txtHomePhone.Text) ? false : true;
}
You have to set the ControlToValidate to some TextBox.
<asp:CustomValidator ID="CustomValidator1" OnServerValidate="validatePhone" EnabEnableClientScript="false" runat="server" ErrorMessage="Home or Cell Phone is Required" ControlToValidate="txtHomePhone"/>
Check out this article. Basically you need to wire up the client side validation.
Add the following just before the closing form tag changing the control names as needed:
<%-- This configures the validator to automatically--%>
<%-- update when either of these controls is changed --%>
<script type="text/javascript">
<!--
ValidatorHookupControlID("<%= MyControl1.ClientID %>",
document.getElementById["<%= CustomValidator1.ClientID %>"]);
ValidatorHookupControlID("<%= MyControl2.ClientID %>",
document.getElementById["<%= CustomValidator1.ClientID %>"]);
//-->
</script>
Alternatively use this control
Issue was completely my fault. On my submit button the final thing I do is a Response.Redirect. The message was coming up, but then the Thank you page was being presented. Now only doing the Response.Redirect if the customvalidator returns true.

Enable/disable RequiredValidator on client-side / CustomValidator not firing

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;
}
}

ASP.Net: Ajax check for registration as a user?

I have an user registration on my site.
I want to look it cool, so my plan is, that after a textbox is left, a green or red sign right behind the textbox tell the user if e.g. the username is unused, the email-adress is unused, the password is correct entered twice and so on.
Yes, I know the validation controls, but there are only a bunch of functions, isn't it? E.g. for checking if the email-adress is unused I must check by database and so on...
Any Ideas?
I would wrap the whole thing in an update panel, this is something I do quite often...
<asp:scriptmanager runat="server" id="sm1" />
<asp:updatepanel runat="server" id="up1" updatemode="Conditional">
<contenttemplate>
<asp:textbox runat="server" id="tbUsername" autopostback="true" ontextchanged="tbUsername_TextChanged" />
<asp:customvalidator runat="server" text="Email already used" id="cusValEmail" />
<asp:textbox runat="server" id="tbPassword" />
</contenttemplate>
</asp:updatepanel>
and in the code behind
protected void tbUsername_TextChanged(object sender, EventArgs e)
{
//call DB etc and mark validator as needed
cusValEmail.IsValid = false;
}
The key is setting the textbox autopostback to true and utilising the ontextchanged event.
A simple way of doing this would be to create a controller action (if you are using MVC) or a page (if you are using regular asp/asp.net) that you post the username, e-mail address, etc to that returns a simple plain-text colour value - red or green, depending on whether all the parameters have been posted are ok. You could then apply that to the colour-style of the box. If you don't have/want that to be an https call then I probably wouldn't include the passwords in that, you ajax return code could maybe say
if (<password are equal>)
{
set style-colour to the return value
}
else
{
set to red
}
or probably, even better, something like
if (<passwords are equal>)
{
run ajax call
}
else
{
set style-colour to red
}
and the the ajax return sets the colour to the return value, that way you also save a round trip to the server if the passwords aren't equal
Any reason you want/need to do this via ajax rather than a regular postback (you could use an update panel to do a partial postback)?

How do I fire an ASP.NET custom validator from JavaScript?

I want to code a function in javascript that every time I call it in the webform it fires up an specific validator in that same webform.
<asp:RequiredFieldValidator ID="passwordRequiredFieldValidator" runat="server"
ErrorMessage="* Password Required!"
EnableClientScript="true" CssClass="errorText"
ControlToValidate="passwordTextBox">
</asp:RequiredFieldValidator>
To fire this validator use:
window.ValidatorValidate(window.passwordRequiredFieldValidator);
Further example:
function ValidatePassword() {
window.ValidatorValidate(window.passwordRequiredFieldValidator);
var valid = window.passwordRequiredFieldValidator.isvalid;
alert(valid);
}
if (Page_ClientValidate('Validation Group'))
{
//Your valid
}
The "CustomValidator" control lets you use javascript to validate your form. If you do this you should also do the same validation on the server so that the user can't just disable javascript to bypass the validation errors.

Resources