views:

79

answers:

4

Hi All,

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.

A: 

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
}
abatishchev
But I can't put <asp:regularexpressionValidator> on client side, I have to do same validation on server side .
Zerotoinfinite
@Zerotoinfinite: Do you mean - can't put in markup? Why not? (just interesting). Also you can use `CustomValidator` - see my updated post.
abatishchev
@abatishchev: Looks like you edited your answer just to match what @webdude answered before you...
Darksider
I am already using javascript function on the client click of that button and in this case my regularExpressionValidator is not working, for the same I have to put it on the server side.
Zerotoinfinite
@Darksider: No, I don't. Also his answer is scant and is a medley of C# and VB.NET syntax o__O
abatishchev
+1  A: 

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

axk
+1  A: 

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.

David M
+2  A: 

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

WebDude