2
votes

I have a pretty straightforward aspx form that collects name, address, email etc and I'm trying to do server-side validation using asp controls. It's working (I think?) and I know I need to do it server-side, but I'm not sure exactly where to put the regex for the actual requirements for each field.

Here's one of my fields as an example:

<div class="form-group">
     <asp:Label runat="server" AssociatedControlID="FirstName" CssClass="col-md-2 control-label">* First Name</asp:Label>
     <div class="col-md-3">
          <asp:TextBox runat="server" ID="FirstName" CssClass="form-control" />
          <asp:RequiredFieldValidator runat="server" ControlToValidate="FirstName"
               CssClass="text-danger" ErrorMessage="First Name field is required." Display="Dynamic" />
     </div>
</div>

I've been using an asp:RequiredFieldValidator and the client-side validation part is working perfectly. The form knows when the user has or hasn't entered something into my required fields and notifies them accordingly before sending anything to the server. I've tested it by putting a label on my page called "valid" and then putting this into my submit button click event:

if(Page.IsValid)
{
     valid.Text = "it's working";
}

And when I fill out the required fields my label does indeed appear and say it's working. However, the asp:RequiredFieldValidator, by definition, only indicates whether my required fields have a value of some kind. It does nothing to check the formatting of what the user entered.

I do need to make certain fields required and I like how the client-side validation part is working. But I also need to do server-side validation and use regex somewhere in the mix to make sure they actually entered an e-mail address in the e-mail field and actually put numbers in the zip code field etc.

I'm fairly new to ASP.NET and it's starting to feel like I'm fighting it. I don't want to fight it. I want to use the available tools to do pretty standard server-side validation, I'm just not exactly sure where to put the regex.

Can anyone help?

Thanks

2

2 Answers

1
votes

Web Forms validators add client and server side code automatically to cover both bases. In the case of your RequiredFieldValidator, it simply checks the value is present on the client and if you also call "Page.IsValid" when Page_Load is fired it will do so on the server end.

What you are after is the "RegularExpressionValidator". You can use one or both on the page depending on what you are trying to achieve.

Here's a good example: https://msdn.microsoft.com/en-us/library/ff650303.aspx

0
votes

You can write your own validator, client and server side. Check out CustomValidator

Example:

<asp:CustomValidator runat="server" id="CustomValidator" ValidateEmptyText="false" OnServerValidate="customValidation_event"  ClientValidationFunction="customValidation_client" />

And add javascript function and validation method in your code-behind.