Analysis on the use of CustomValidator, an ASP. NET data verification control

Source: Internet
Author: User

ASP. NET data verification control is powerful because when performing form data verification in ASP, developers usually have to write a set of validation rules themselves, and then copy the code to ASP code to verify the form. This verification method is not very convenient. Fortunately, ASP. NET solves this problem, which is the data verification Web control.

Overview of the CustomValidator Control for ASP. NET data verification

Simply using the first four data verification controls mentioned above, we can implement the verification requirements for most of the data forms we generally develop. However, sometimes we need to verify some complicated forms. Imagine that we have a complicated questionnaire, which contains many single-choice buttons and multiple-choice buttons. Some multiple-choice buttons correspond to my hobbies, for example, swimming, sports, reading, etc. The survey table is intended for all the hobbies of the respondents. Below these options, the prompt is as follows: "If you have two hobbies: sports and swimming, select when to start learning swimming ", put some radio buttons Under these texts that identify the age group. Whether these buttons are valid depends on the selection of the Multi-choice button we mentioned earlier. In the above verification, we need to use the CustomValidator data verification control.

All ASP. NET data verification controls have a "ControlToValidate" control attribute that needs to be set to specify the form items to be verified in the form. In the CustomValidator data verification control, you need to do the following:

1. Read the value of form items that require CustomValidator verification;

2. perform the verification operation;

3. Determine whether the items in the verified form meet the verification requirements.

In other built-in controls, the user does not know or ignore the above steps. However, when using CustomValidator, we need to implement the above steps by ourselves. To implement the above steps, we need to compile a server-side data verification function. The style of this function is as follows:

 
 
  1. Sub FunctionName(sender as Object, args as ServerValidateEventArgs)  
  2.  
  3. ……  
  4.  
  5. End Sub 

Note that the args parameter of the above function is the second parameter of the FunctionName function. This parameter has the following two attributes:

1. Value: the Value of the verified data form.

2. IsValid: verify whether it passes. If the request passes, the IsValid value is True. If the request fails, the IsValid value is False.

When using CustomValidator, we must not only set the "ControlToValidate" attribute, but also set the OnServerValidate event to process data verification actions on the server.

Create a simple ASP. NET data verification control CustomValidator

Suppose we have created a mathematics-related website. On this website, we ask our viewers to provide their favorite prime numbers to increase the access volume of our website. In ASP. NET, there is no ready-made server-side data verification control that can specifically verify the quality. In this way, we need to use the CustomValidator control.

The following example is used to verify whether the number entered by the user is a prime number. In this form, there is a TextBox Control and a Button control for user input data, a CustomValidator Control for verifying whether it is a prime number, and two CompareValidator controls for ensuring that user input is a positive number.

 
 
  1. <Script language = "vb" runat = "server">
  2. Sub btnSubmit_Click (senderAsObject, eAsEventArgs)
  3. If Page. IsValid then
  4. Response. Write ("<font color =" red ">
  5. <I> "& txtPrimeNumber. Text &"Is, Indeed, a good prime number.
  6. </I> </font> ")
  7. Else
  8. Response. Write ("<font color =" red ">
  9. <I> "& txtPrimeNumber. Text &"Is<B> not </B>
  10. A prime number. </I> </font> ")
  11. End If
  12. End Sub
  13. Sub PrimeNumberCheck (senderAsObject, argsAs 
  14. ServerValidateEventArgs)
  15. Dim iPrimeAsInteger = Cint (args. Value ),
  16. ILoopAsInteger, iSqrtAsInteger = CInt (Math. Sqrt (iPrime ))
  17. For iLoop = 2 to iSqrt
  18. If iPrime mod iLoop = 0 then
  19. Args. IsValid = False
  20. Exit Sub
  21. End If
  22. Next
  23. Args. IsValid = True
  24. End Sub
  25. </Script>
  26. <Form method = "post" runat = "server">
  27. Enter your favorite prime number:
  28. <Asp: textbox id = "txtPrimeNumber" runat = "server"/>
  29. <% -- Create the CustomValidator control -- %>
  30. <Asp: CustomValidator runat = "server"
  31. Id = "custPrimeCheck"
  32. ControlToValidate = "txtPrimeNumber"
  33. OnServerValidate = "PrimeNumberCheck"
  34. ErrorMessage = "Invalid Prime Number"/>
  35. <%-- Create two CompareValidator controls: the first one must be a number;
  36. Second, ensure that the input is positive -- %>
  37. <Asp: CompareValidator runat = "server"
  38. Id = "compPrimeNumber" Operator = "DataTypeCheck"
  39. Type = "Integer"
  40. Display = "Dynamic" ControlToValidate =
  41. "TxtPrimeNumber" ErrorMessage =
  42. "You must enter an integer value."/>
  43. <Asp: CompareValidator runat = "server"
  44. Id = "compPrimeNumberPositive" Operator = "GreaterThan"
  45. Type = "Integer"
  46. Display = "Dynamic" ValueToCompare = "0"
  47. ControlToValidate = "txtPrimeNumber"
  48. ErrorMessage = "You must enter a value
  49. Greater than zero. "/>
  50. <P> <asp: button id = "btnSubmit" runat =
  51. "Server" OnClick = "btnSubmit_Click" Text = "Submit"/>
  52. </Form>

If you are not familiar with determining the prime number, you may be confused about how to handle the above PrimeNumberCheck events. First, pass the data entered in txtPrimeNumber through The args of the event. value is sent to txtPrimeNumber. Then, the square root of the user input is opened, and the number entered by the user is divided by every number between 2 and the square root of the result just calculated. If the result is zero, the number entered by the user is not a prime number, and the value of args. isValid is set to False. If all the values are zero, the input is valid and the value of args. isValid is set to True.

Client verification of ASP. NET data verification controls

One of the major features of ASP. NET's built-in data verification controls is that all their verification is performed on the client without going through the server. The error verification of the CustomValidator control is completely implemented on the server side. It must be realized that, whether or not data verification is implemented through the client, server-side data verification will certainly be generated. The client verification function is added to make our data verification controls more friendly.

To implement the client-side verification function, we must use JavaScript or VBScript to write a script function. Because VBScript only supports ie browsers, we use JavaScript to compile this function:

 
 
  1. ﹤ script language=“JavaScript” ﹥  
  2. ﹤ !--  
  3.   function CheckPrime(sender, args)  
  4.   { var iPrime = parseInt(args.Value);  
  5. var iSqrt = parseInt(Math.sqrt(iPrime));  
  6. for (var iLoop=2; iLoop﹤ =iSqrt; iLoop++)  
  7.   if (iPrime % iLoop == 0)   
  8.   { args.IsValid = false;  
  9.  return;  
  10.   }  
  11.   args.IsValid = true;  
  12.   }  
  13. // --﹥  
  14. ﹤ /script ﹥ 

In this example, enter the number 6 and press the "Tab" button. In the High Version browser, we will see the error message from the CustomValidator control. In this way, our CustomValidator control also has the client verification function. In the above Code, we may have noticed that we have not defined the data sender and args types, because there is no strict data type definition in the scripting language.

To verify client data, add the following statement in the CustomValidator control definition: ClientValidationFunction = "CheckPrime". Here, the client verification function of the custom verification control is specified. In this example, the previously defined "CheckPrime" function is the client verification function.

Summary of the use of the ASP. NET data verification control CustomValidator

The preceding section describes the use of CustomValidator, the most flexible data verification control in ASP. NET, and the implementation of the CustomValidator control on the server side and client side. Although in actual development work, we may use ASP. NET's built-in data verification control can almost fully meet our development requirements, but if you can understand the use and characteristics of the CustomValidator control, it will be more conducive to solving the data verification problems encountered at work.

The basic information about the use of the ASP. NET data verification control CustomValidator is described here. I hope it will help you.

  1. Some discussions about ASP. NET code separation
  2. Experience in ASP. NET code separation
  3. Detailed research on ASP. NET data verification technology
  4. Application of ASP. NET code separation in website construction
  5. Analysis on ASP. NET code optimization

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.