Validating user input with c
Before accepting data from over the network you need to ensure all of the required fields have been filled out and conform to your formats and business rules. NET provides a number of validation controls to ease the burden of performing validation on both sides of the network. To walk along with the example, create a new web application in Visual Studio . Once the application is setup, right click on the empty web form, select Properties from the context menu, and change the Page Layout property to Flow Layout. Notice we need to check the Is Valid property of the base class before performing any critical action in the submit event.Place four controls from the Web forms section of the Toolbox onto the form. If Is Valid returns a value of true then all of the validation checks were successful.The associated control is set by right clicking on the validator and selecting Properties from the context menu. The rest of the validation controls provided by ASP.In the Properties dialog box find the Control To Validate property and select First Name Text Box from the drop down list. We can set other properties, such as the Error Message property, and the final ASPX source code should look like the following. NET work in a similar fashion to what we've seen above. If the client's web browser is of executing client side Java Script, the first validation pass occurs on the client.The cancel button has a Causes Validation property. As we mentioned in the beginning of the article, validation can occur twice: once on the client’s machine and once on the server. Client side validation provides quick feedback for the user.Validation occurs when a user clicks any Button control by default, but you can change this behavior by setting the Causes Validation property to false. Whenever the user presses a button on the form, the script executes the validation checks for each validation control on the form.You need to check the Is Valid property to know if a validation check failed.Validation is complete by the time you reach a click event.
For this first example we do not need to place much code into the code-behind file. NET runtime does not waste time processing a request with invalid information.
As we will see later in the code-behind file, the Cancel Button 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. If any one of the validation controls on a form fails, the script cancels the postback operation and displays error messages on the form.
Notice in the following screen capture, we can see the Required Field Validator error message display on the form. The user does not wait on a server round trip to discover errors.
Html Controls; namespace Web Data Validation When the user clicks the Cancel button we clear the Text Box control and allow the user to start over.
There are good reasons to always execute validation checks on the server.