We help IT Professionals succeed at work.

Server Side Validation

Hello Experts,

Is there anyway someone can show me an example to use Server Validation? I'm currently creating an online Form and I have jQuery setup now for Client Side Validation but want to implement Server Side to make sure that if Javascript is turned off and also to prevent user from not using jquery even if it's not disabled.

Below is what I need to check using Server Side Validation. I'm using ASP.NET 4.0 and C#. I don't want to use any kind of Validation from ASP.NET since it's Client side, prefer to use jQuery.

txtName - required field

ddlGender - default value loaded from Page_Load is -- Select --, this field is also required and the ID associated in the DB for -- Select -- is 2.

ckBoxRace - this field is required and user MUST select one value.

txtDOB - required field. user needs to enter a correct date format of xx/xx/xx.

txtPhone - required field. user needs to enter a correct US format. Exampe: xxx-xxx-xxxx. User is not allowed to enter xxxxxxxxxx or xxx.xxx.xxxx.

Thanks in advance!
Comment
Watch Question

Eric FlammOwner

Commented:
Actually, ASP.Net validation controls operate both client-side and server-side (see http://msdn.microsoft.com/en-us/library/aa479013.aspx for a discussion of ASP.Net validation controls). Just configure OnServerValidate to point to a method in your code-behind, and the validator automatically invokes the validation code and pass content to the method arguments.

So, then you write server-side validation methods for each control, e.g.

Sub ValidateName(sender As Object, args As ServerValidateEventArgs)
       Try
          Dim sName As String=args.ToString();
          args.IsValid = sName.Length>0;
       Catch ex As Exception
          args.IsValid = false
       End Try
    End Sub

Open in new window


That should get you started - let me know if the approach for any of the other items is a challenge.

Author

Commented:
Hi eflamm,

Sorry, I'm not sure I understand what you mean with the code snippet you supplied. I'm also not sure what you mean by "Just configure OnServerValidate to point to a method in your code-behind, and the validator automatically invokes the validation code and pass content to the method arguments."
I think you have to use Validation Controls provided by ASP.Net. Refer following links for more information

http://www.w3schools.com/aspnet/aspnet_refvalidationcontrols.asp
http://msdn.microsoft.com/en-us/library/bwd43d0x.aspx

- Deepak Lakkad
Eric FlammOwner

Commented:
OK - here's the longer version - did you look at the link I provided (that's where the snippet came from)?

ASP.net validation controls do both server-side and client-side validation - the client-side is handled by Javascript generated by the control; the server-side is built into control. The sample I provided is specific to the custom-validation control, which you can use to validate almost any condition (or set of conditions).

Use the ASP.Net validation controls as described in the link I posted above - if you need more complex validation, use the custom validator on the control that needs the complex logic - when the validator fires (typically on submit, but many events can trigger validation), the method called out in the OnServerValidate value of the validator will be called; this method sets Page.IsValid to either true or false. Then, you can test that value in the Page_Load value and either alert the user to the error or take some other corrective action.

Basically, I wanted to point out that you are wrong about ASP.Net validator controls - they provide both server-side and client-side validation; your concern about using the built-in validators while using jQuery does not make much sense to me.

For your date and phone fields, you can use the RegEx validator control. I think you'll find there are appropriate validators for each of your controls.

Like they say in the commercial - "Try it, you'll like it"

Author

Commented:
@deepaklakkad:

So are you saying that I can have BOTH Client and Server Side Validation assigned to a single ASP.NET Custom Validator such as the following example below?

If so, then how and where can I find JavaScript / Server Side code to handle the types of Validation that I need as mentioned above in my original post?

The following attached code was taken from the link you mentioned deepaklakkad http://msdn.microsoft.com/en-us/library/bwd43d0x.aspx

If you see what I did I took that Custom Validator Control and added "OnServerValidate" and "ClientValidationFunction" to it. Is this okay?


HTML MARKUP:

<asp:textbox id="TextBox1" runat="server"></asp:textbox>
<asp:CustomValidator id="CustomValidator1" runat="server" 
  OnServerValidate="TextValidate" 
  ClientValidationFunction="validateLength"
  ControlToValidate="TextBox1" 
  ErrorMessage="Text must be 8 or more characters.">
</asp:CustomValidator>

Open in new window

CLIENT VALIDATION:

<script type="text/javascript">
  function validateLength(oSrc, args){
   args.IsValid = (args.Value.length >= 8);
}
</script>


SERVER SIDE VALIDATION:

protected void TextValidate(object source, ServerValidateEventArgs args)
{
    args.IsValid = (args.Value.Length >= 8);
}

Open in new window

Eric FlammOwner

Commented:
That looks OK to me. Do you use a code-behind page in ASP.Net (I think it's the default). All that means is that the server-side code is stored in a separate file - if your page is default.aspx, then the code-behind would be default.aspx.cs. If that's the case, then the server side procedure (TextValidate) should be in the code-behind file. It all gets put together when the site is compiled anyway; I just don't like to have server side code in my web page files.

I tried the code you posted - I added a Submit button to the HTML (with CausesValidation=True) to test the server side code. I also added a label that I could update through the code.

Here's my default.aspx.cs:
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
       
    }
    protected void TextValidate(object source, ServerValidateEventArgs args)
    {
        args.IsValid = (args.Value.Length >= 10);
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
            lblResult.Text="Page is valid";
        else
            lblResult.Text="Page is Not Valid";
    }
}

Open in new window

Note that I changed the server side test to >=10 - that way, you can pass the client test, but still fail the server side test. Of course, you could do something way more interesting on the server side, like passing the value to database and seeing if it matches a known ID value.

I put a breakpoint on the TextValidate method, so I could step through the code - it looks to me like it fires before the server processes the Button1_Click method, which is what you want.

Author

Commented:
Ok, now how or what would the code look like if I needed to make sure a value was getting selected from a dropdown list control and checkbox/radiobox controls?
Eric FlammOwner

Commented:
From the previously provided link:
Using the InitialValue Property with a DropDownList Control

A good way of using the InitialValue property is with the DropDownList server control. For instance, a drop-down list might have a default value that is not an empty value (by default, some text appears in it). An example of a drop-down list with the RequiredFieldValidator that uses the InitialValue property is illustrated in Listing 5.

Listing 5: Using the RequiredFieldValidator server control with the Drop-DownList server control

<asp:DropDownList id="DropDownList1" runat="server">
   <asp:ListItem Selected="True">Select a profession</asp:ListItem>
   <asp:ListItem>Programmer</asp:ListItem>
   <asp:ListItem>Lawyer</asp:ListItem>
   <asp:ListItem>Doctor</asp:ListItem>
   <asp:ListItem>Artist</asp:ListItem>
</asp:DropDownList>
  &nbsp;
<asp:RequiredFieldValidator id="RequiredFieldValidator1"  
  runat="server" ErrorMessage="Please make a selection"
  ControlToValidate="DropDownList1"
  InitialValue="Select a profession">
</asp:RequiredFieldValidator>

Using this kind of construct enables you to place a description of the actions required in the drop-down list and also requires the user to make a selection from the choices. To get past the validation process, the user must make a selection other than the Select a profession choice. If the user doesn't enter a profession, an error message is returned (see Figure 3). It takes a lot of code to write your own JavaScript function for this procedure, and that JavaScript also has to be browser-independent. With ASP.NET, the RequiredFieldValidator server control takes care of that.

To validate a checkboxlist (and should work against a radiobutton list, more or less) - add a custom validator with no "Control To Validate"; add a servervalidate method - here's mine:
 protected void CustomValidator2_ServerValidate(object source, ServerValidateEventArgs args)
    {
        lblCB.Text = string.Empty;
        foreach (ListItem li in CheckBoxList1.Items)
        {
            if(li.Selected)
            lblCB.Text+=string.Format("{0}\n",li.Text);
            if (lblCB.Text.Length > 0)
                args.IsValid = true;
            else
                args.IsValid = false;
        }           
        
    }

Open in new window


This is your only choice for checkboxlist - for radiobuttonlist you can use the other validators (like the CompareValidator) which require a control to validate.

Author

Commented:
Hi eflamm,

Ok, before I try that for the CheckBox List I'm having trouble getting the Server Side Validation working. Please see my code below that I"m trying to implement just for the txtName Control for now.

If I enter a character that is lower than 8 and try to click on the submit button then it works BUT if I DO NOT enter anything into the TextBox Control than the form submits. I need to prevent the form from submitting IF NO DATA is entered in the TextBox Control txtName. Is this possible, if so how?
HTML MARKUP:

        <asp:Label ID="lblName" runat="server" Text="NAME" CssClass="label"></asp:Label><br />
        <asp:Label ID="lblNameRequired" runat="server" Text="REQUIRED" CssClass="labelrequired"></asp:Label>
        <br />
        <asp:TextBox ID="txtName" runat="server" CssClass="textbox"></asp:TextBox>&nbsp;&nbsp;<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Required" ControlToValidate="txtName" OnServerValidate="CustomValidator1_ServerValidate"></asp:CustomValidator>
        <br />
        <br />
        <asp:Label ID="lblResult" runat="server"></asp:Label>
        <br />
        <asp:Button ID="btnSubmit" runat="server" Text="Submit" 
            OnClick="btnSubmit_Click" />

Open in new window

CODEBEHIND:

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
            lblResult.Text = "Page is valid";
        else
            lblResult.Text = "Page is Not Valid";
    }

    protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
    {
        args.IsValid = (args.Value.Length >= 10);
    }

Open in new window

Eric FlammOwner

Commented:
Try adding ValidateEmptyText=true to the attributes of the Custom Validator control

Author

Commented:
Hi eflamm,

Yes, setting ValidateEmptyText = true worked fine. Is there a site that talks about different ways to Validate using Server Side so that I can learn from?

I see the MSDN site that talks about it but was wondering if there where more that you could refer to me. Also, as far as validating the type of content a user can enter in an control am I better of using the ASP.NET Validation Controls for that instead of writing code for it?

Author

Commented:
Hi eflamm,

Sorry, I take that back, it's buggy. Please see my example below.

If I DO NOT have anything inside the curly brackets then I can submit without entering any data which I need to prevent. I also added the ValidateEmptyText=true to the Custom Validator but if Javascript is turned off then it does not work.
    protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
    {
    }


If I have this inside the curly brackets then the code will work as long as I have 5 characters in the TextBox Control.
    protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
    {
        args.IsValid = (args.Value.Length >= 5);
    }

Author

Commented:
Hi eflamm,

Ok, I tried the following code below and it prevents me from NOT entering data in the txtName Control and it also checks to make sure values entered are >=8. Is this code ok to use or would you improve it and if so what would you change?
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
    {
        args.IsValid = (txtName.Text != string.Empty) && (args.Value.Length >=8);
    }

Open in new window

Eric FlammOwner

Commented:
It seems like you should be able to do args.Value!=string.Empty, but txtName. Text should work fine. I gather you did not want to add a second validator (RequiredFieldValidator) to the control - like all validators, it would provide both client- and server-side functionality without the extra code in the Custom Validator. The other advantage of using multiple validators is that you can vary the message based on the exception:
Required Field Validator=>"Name is required!"
Custom Validator=>"Name must be 8 characters or longer"
You could probably change the validation message from the code-behind based on the different comparisons - I think that's a question for a different thread.

Author

Commented:
Hi eflamm,

args.Value!=string.Empty did NOT work.

I can only get args.IsValid = (txtName.Text != string.Empty); to work.

Also, the RequiredFieldValidator will ONLY work if JavaScript is Enabled. If JavaScript is Disabled then how am I suspose to validate the Server Side code using the RequiredFieldValidator???
Owner
Commented:
As I understand it (and I really haven't spent much time doing server-side only validation), the RequiredFieldValidator WILL do server-side validation whether or not Javascript is available to client-side validation, and you don't have to code the server-side logic - it's built into the validator. You only need to write server-side logic for the custom validator control, because it doesn't know what it's supposed to do. The RequiredFieldValidator knows how to validate a field (it's in the designer generated code - you can dig into it in debug if you really want to) - so it tries to do the client-side validation first using Javascript; if the page posts (either because it's valid or because Javascript is turned off), if runs its server-side validation and, if that test fails, it sets Page.isValid to false and you can use that to direct your server-side code. Here's an older post that seems like a good walkthrough of this approach.

Author

Commented:
Hi eflamm,

Ok, I was able to get the RequiredFieldValidation to work when I turned JavaScript off by using Page(.IsValid).

Now, before I close this post, can you help me witih a similar issue or should I create another post?

I would like to add a CSS style to my TextBox and DropDownList Controls which would add a BG color of Red and a dark Red border to each of those controls if the Controls are Required and nothing entered in. Is this possible and if so how.
Eric FlammOwner

Commented:
Definitely sounds like another post ;-). I think you could use jQuery to make it happen - have a style that applies to all required controls then clear it when the user makes an entry. Not sure how you could do it without Javascript.

Author

Commented:
eflamm,

Yes, it works fine with jQuery but not if JavaScript is Disabled. If i'ts Disabled then it does the CSS style is not applied :(
Distinguished Expert 2019

Commented:
The idea of client/server validation is that you hope that javascript is not disabled such that the input to your form will be validated on the client side and more user friendly versus the user types in the data clicks submit, and then receives the same form back saying you have incorrect data in section 1 or marked by a red asterisk.
With client side the error could be pointed out to the user immidiately even preventing the user from entering incorrect data i.e. you have a number field and the user tries to input characters. etc.

The server validation is the back stop in the event the client validation is unavailable to avoid inserting invalid data.
Using the client side validation with a special input i.e. the javascript when validation is correct, will set a hidden/option indicate it validated such that the server validation could be minimized to specific items just to be sure.

Server based validation also removes the complexity of having validation match the browser functionality that is accessing the page.
Eric FlammOwner

Commented:
Please award the points for this solution and close this question out. You can certainly ask your question about style manipulation in a separate thread.