Search code examples
asp.netregexrequiredfieldvalidator

ASP.NET Regular Expression Validator VS Required Field Validator OR both?


I don't really know if I should be using both the Regular Expression Validator and Required Field Validator or what? I have just a normal form in ASP.Net (Visual Studio). I want to make sure the user types in the correct characters, such as for a phone number (which is why I want the reg ex control), but I also want the field to be required. So should these be combined or what is the best way to do this?

Right now I just have the required part working, like this:

 <asp:RequiredFieldValidator runat="server" id="RequiredFieldValidator2" 
                    controltovalidate="TextBoxLocation" errormessage="Required" 
                    />

Solution

  • You can use both of them, but make sure to add Display="Dynamic" on both of the controls.

    <asp:RequiredFieldValidator runat="server" id="RequiredFieldValidator1" 
                    controltovalidate="TextBoxLocation" Display="Dynamic" errormessage="Required" 
                    />
    <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ErrorMessage="Enter valid Phone number" ControlToValidate="TextBoxLocation" Display="Dynamic" ValidationExpression="^[01]?[- .]?(\([2-9]\d{2}\)|[2-9]\d{2})[- .]?\d{3}[- .]?\d{4}$" ></asp:RegularExpressionValidator>