[ASP.NET]Validation Controls (轉錄)

  • 9631
  • 0

[ASP.NET]Validation Controls (轉錄)

原文出處:ASP.NET Validation Controls – Important Points, Tips and Tricks

感想:不只教你怎麼用,還跟你說,為什麼要這樣設定。(包括server端與client端的原理)

內容涵蓋6種Validation Control:

  1. RequiredFieldValidator
  2. RegularExpressionValidator
  3. CompareValidator
  4. RangeValidator
  5. CustomValidator
  6. BaseValidator

摘要:(真的太重要了!這一篇!一不小心就貼了很多....很難捨棄.....)

  1. 要使用Page.IsValid,也就是server端驗證,以避免javascript失效或被停用。
    • Always use Page.IsValid before submitting data. Apart from the other benefits, using it prevents submitting data from old browsers that do not support javascript.
  2. 解釋顯示錯誤訊息的方式,None、Static與Dynamic的差異。
    • The display property for the ASP.NET validation controls has 3 settings: None, Static(default), and Dynamic. ‘Static’ outputs HTML code (related to error) at all times even when no error has occurred. So when there is more than one validation control placed next to the field, the first validation control occupies screen space even when there is no error. In case the second validation control fires an error message, the message is pushed away from the control since the first validation control is occupying screen space.
      Set the ‘display’ property of a validation control to ‘Dynamic’. This property renders the error message with the attribute display:none; It helps you to display the error message next to the control .
  3. 如何讓一個按鈕不觸發驗證,例如「回上頁」、「清除」、「關閉」等按鈕
    • To prevent validation to occur on the click of the Cancel button, set the ‘CausesValidation’ property to false
      
    
      
  4. Use the ‘InitialValue’ property of the RequiredFieldValidator to validate controls like combobox which have a default value.
    • For eg: If your combobox has a default item called “--Select --“ and you want that the user should select a value other than the default value before submitting the form, then set the ‘InitialValue’ property of the RequiredFieldValidator to “—Select—“.
  5. 解釋如何使用正則表示驗證,包括根據文化限制採不同規則
    • A RegularExpressionValidator can be used to handle string patterns. For eg: A Name textbox that should accept a maximum of 30 characters with only alphabets, space, fullstop(.) and a ‘(apostrophe). A regularexpression like ‘^([a-zA-z.'\s]{2,30})$’ does the trick.
      However when you are using Localization and using a language like Arabic, you have to often provide for validating characters in a different dialect. You can solve this using the following technique:
      • In the Resource.resx file, create a resourcekey called ValidName giving it a value of ^([a-zA-z.'\s]{2,30})$
      • In the Resource.ar-EG.resx file, use the same key but with a diff value ^([\u0600-\u06FF.'\s]{2,30})$
    • Use it in your page using the following way. Observe the bold text:
    • Display='Dynamic'ErrorMessage='Invalid’
      ValidationExpression='<%$ Resources:Resource, ValidName %>'SetFocusOnError='True'></asp:RegularExpressionValidator>
    • When the user selects English, he can enter only A-Za-z. Similarly for Arabic, he can enter only the Arabic characters and not English.
  6. 如何關掉client端的驗證
    • The validation controls provide both Server and Client Side validation. To turn off client-side validation, set the ‘EnableClientScript = false’
  7. 如何使用CompareValidator來驗證格式,或比較數值
    • Use CompareValidator to validate date with format of "dd/MM/yyyy".
      The validator uses the CultureInfo object of the thread to determine date format. So what you need to do is to set the desired culture format in the Page directive
      
    
      
  8. 錯誤訊息可以使用圖像檔或聲音檔來表示,(聲音檔耶!超酷!)
    • Instead of the textual error message, you can even add an image or sound to your validator control. The Text and Error Message property accepts HTML tags.
            <br />
    <asp:RequiredFieldValidator ControlToValidate="TextBox1" EnableClientScript="false" ID="RequiredFieldValidator1" runat="server" Text="<bgsound src='C:\Windows\Media\Windows Error.wav'>"></asp:RequiredFieldValidator>
    Just make sure that the EnableClientScript="false" when you want a sound instead of a text message.
  9. 怎麼使用ValidationGroup來區分不同驗證群組
    • If you have two set of forms (eg: Login and Registration) in a single page and want to keep the validation of the two groups separate, use ‘ValidationGroups’. All you need to do, is to specify a common group name for a set of controls that you want to validate separately.
  10. 怎麼使用RangeValidator
    • Other validator controls like CompareValidator, RangeValidator etc. do not provide a way to detect if the field is blank or required. The only way is to do this is to add a RequiredFieldValidator along with the other validator controls.
      However one exception being the CustomValidator which provides a property called ‘ValidateEmptyText’. Just set it to true and it validates the field even if the user has kept the field blank.
  11. 怎麼使用ValidationSummary,來將錯誤訊息統一顯示在某個區塊
    • If you want your validation error message to appear in the ‘ValidationSummary‘ control, then set the ‘ErrorMessage’ property on that validation control. Also, setting 'ShowMessageBox = true' on the ValidationSummary enables you to display a popup alert.
  12. 怎麼自訂一個客製化的Validator,使用BaseValidator
    • In order to create a CustomValidationControl you have to derive from the 'BaseValidator' class and implement the 'EvaluateIsValid()' method.
  13. 當驗證錯誤時,將滑鼠指標focus在驗證錯誤的control上
    • In case of an error, the validation controls allow you to set focus on a control in error using the ‘SetFocusOnError’ property.

blog 與課程更新內容,請前往新站位置:http://tdd.best/