NET provides a number of validation controls to ease the burden of performing validation on both sides of the network. These controls are the main focus of this article. Validation Example To walk along with the example, create a new web application in Visual Studio.
Design the Form Place four controls from the Web forms section of the Toolbox onto the form. This RequiredFieldValidator forces the user to enter text into the control associated with the validator. The associated control is set by right clicking on the validator and selecting Properties from the context menu. First name is now a required field in the form.
We can set other properties, such as the ErrorMessage property, and the final ASPX source code should look like the following. Validation occurs when a user clicks any Button control by default, but you can change this behavior by setting the CausesValidation property to false. As we will see later in the code-behind file, the CancelButton will clear all of the fields on the form, and we do not want to validate any of the fields when the user presses this button. Notice in the following screen capture, we can see the RequiredFieldValidator error message display on the form.
This is the exact position the error message will appear if validation fails. Adding the Code For this first example we do not need to place much code into the code-behind file.
We can double click on both of the Button controls on the form to add event handlers for the click events. The complete listing for WebForm1. Button CancelButton; protected System. This call is required by the ASP. If IsValid returns a value of true then all of the validation checks were successful. The RequiredFieldValidator fails when the value in the associated control matches the value of the InitialValue property of the RequiredFieldValidator.
NET work in a similar fashion to what we've seen above. As we mentioned in the beginning of the article, validation can occur twice: It is important to understand why ASP. NET will go to this trouble. Client side validation provides quick feedback for the user. Whenever the user presses a button on the form, the script executes the validation checks for each validation control on the form. If any one of the validation controls on a form fails, the script cancels the postback operation and displays error messages on the form.
This also improves response time on the server because the ASP. NET will always execute validation checks on the server when a button click event arrives requiring validation. You can disable any of the validation controls by setting the Enabled property to false. There are good reasons to always execute validation checks on the server. Not executing server side validation leaves your application code vulnerable to malicious users. Malicious users might circumvent client side validations in an effort to break-in or damage your servers.
Simply put, never trust the data in an incoming request, and always validate on the server. When validation fails the normal flow of execution continues. You need to check the IsValid property to know if a validation check failed. Validation is complete by the time you reach a click event. There are various validation controls availabe, and we will cover them in the rest of the article. All of the validation controls derive from the BaseValidator class, giving them common methods and properties.
As we mentioned earlier, validation controls execute when the user clicks a Button control, including HTML button controls and server button controls such as the LinkButton and ImageButton.
All of the validation controls must have the ControlToValidate property set before rendering the page or the control throws an exception.
The one exclusion to this rule is the CustomValidator component. RangeValidator The RangeValidator control ensures the value inside a control is within a specified range. There are four key properties to initialize for a RangeValidator.
The MinimumValue and MaximumValue properties control the allowed range of the input. The RangeValidator also has a Type property. This property can take one of the following values: String, Integer, Double, Date, or Currency.
The RangeValidator will first try to convert the values it is examining into the type specified. If the conversion fails, the validation also fails. The RangeValidator does not validate the contents of an input control if the control is empty. In order to require the user to enter a date in this field we will need both the RequiredFieldValidator and the RangeValidator. Without the RequiredFieldValidator, the user does not have to type a value into the HireDateTextBox control, but if they do it must be in a proper date format and in the specified range.
When multiple validation controls reference an input, all the validation checks must pass for the field to be valid. Programmatic Access to Validation Controls Validation controls are available as member variables in the code behind page.
FromDays 7 ; HireDateValidator. The Display property can accept one of three values: None, Static, or Dynamic. If the Display property is set to None, no errors are displayed where the validation control is placed on the form.
We will see an example of using a Display of None later in the chapter when we look at the ValidationSummary control. The Static and Dynamic settings will influence the layout of your page. With the static setting, the control reserves space to display an error message even when no error message is present.
You can use the static setting to ensure your page appearance stays exactly the same when an error message appears. With a Dynamic display, there is no space reserved for the error message. Instead, when validation fails and the control displays an error, the control adds space to the page for the error to appear, which can change the layout of the screen.
Note these two settings are only effective if client side validation is in effect. If you are have server side validation only, the display is effectively dynamic. We are using a Display setting of Dynamic so we reserve no space for the RangeValidator error message.
You can modify these properties in the example program to see the result of using different settings. CompareValidator Use the CompareValidator to compare the value of an input control to either a constant value, or the value in another input control.
You can set the ValueToCompare property at design time or programmatically as the value to compare against. Alternatively, if you want to compare the input value against the value of another control, specify the other control ID in the ControlToCompare property. The value in the ControlToValidate must convert to this type for validation to succeed. For the example we will use the scenario of entering a new password. Since it is difficult for the user to know if they made a typing mistake, users are generally given two input controls: These input values have to match for a valid password.
NET offers some predefined regular expressions in the editor dialog shown below. An example of using the regular expression validator can be seen in the OdeToCode article: CustomValidator You'll need to use a custom validator when none of the built in controls fir your need.
You might need this if your validation requires a database query, or a non-trivial mathematical expression. This property is specific to the CustomValidator, and allows you to present the name of a function existing in client side script. If this property is not set, you can still perform a server side validation. We will need to implement this function in client side script by adding code to the ASPX file inside of a script tag. The function signature must take two variable references.
The second variable passed to the function args is the primary variable we need to make use of. The IsValid member we use to indicate if the validation has passed or failed, while the Value member contains the text in the control to validate. If there was no control specified with the ControlToValidate property of the CustomValidator, the Value property contains an empty string. We simply take the last three characters of the incoming text to see if they contain the string jpg.
If the test is positive, we can pass validation by setting the args IsValid property to true. Adding Server Side Validation To provide a server side implementation of our validation code we need to provide an event handler for the ServerValidate event of the CustomValidator. Right click the control and click Properties on the context menu, then switch to the event view of the Properties dialog.
After double clicking on the ServerValidate event, the IDE should take you to the code-behind file with an empty event handler. The following code provides our implementation.
The method accepts two parameters, with the second parameter of type ServerValidateEventArgs contains the important IsValid and Value properties. Programmatic Validation If the need arises, you can force validation checks to occur. As an example, you may pre-populate a form during initialization with information, and this occurs before the user has a chance to interact with the form.
Without adding an additional step, however, a call to IsValid produces the following error. Calling the Validate method of the Page before checking the IsValid property will fix the exception shown above. This is the same method used by the ASP. Our next step is to put everything together into a working form to submit a new employee record into the database.