In-depth explanation of asp+ verification (transfer from MS II)

Source: Internet
Author: User
Tags bool commit empty implement requires valid zip
asp+ Client API

There is a small API that can be used on the client to achieve a variety of effects in your own client code. Because some routines cannot be hidden, theoretically, you can take advantage of all the variables, attributes, and functions defined by the client-side validation script. However, many of these are implementation details that can be changed. The following summarizes the client objects that we encourage you to use.

Table 3. Client Object

Name Type description
The Page_isvalid Boolean variable indicates whether the page is currently valid. The validation script always keeps the variable up to date.
Page_Validators element Array This is an array that contains all the validators on the page.
The page_validationactive Boolean variable indicates whether validation should be performed. Set this variable to False to turn validation off programmatically.
IsValid Boolean Property Each client validator has this property, indicating whether the validator is currently valid. Note that in the PDC version, this property is mixed with case ("IsValid").


Bypassing client-side validation

One of the tasks you often need to do is to add a Cancel button or navigation button to the page. In this case, even if there is an error on the page, you might want to use the button to submit the page. Because the client button "onclick" event occurs before the "onsubmit" event of the form, it is possible to avoid submitting checks and bypassing validation. The following shows how to use the HTML Image control as the Cancel button to complete the task:

<input Type=image Runat=server
Value= "Cancel"
onclick= "Page_validationactive=false;"
Onserverclick=cmdcancel_click >

There is some confusion about using a Button or ImageButton control to perform this task because the OnClick event is assumed to be a server-side event with the same name. You should set this event in client script:

<asp:imagebutton Runat=server Id=cmdimgcancel
Alternatetext= "Cancel"
Onclick=cmdcancel_click/>

<script language= "JavaScript" >
document.all["Cmdimgcancel"].onclick =
New Function ("page_validationactive=false;");
</script>

Another way to resolve this problem is to set the Cancel button to a certain extent so that it does not trigger a commit event in client script when it returns. The HtmlInputButton and LinkButton controls are examples of this.

Special effects

Another common requirement is that, in the case of an error, some other effect is required in addition to the error message that is displayed by the validator itself. In this case, any modifications you make will need to be made at the same time on the server or client. Suppose you need to add a Label to change the color depending on whether the input is valid or not. The following is how to implement this task on the server:

public class Changecolorpage:page {
Public Label Lblzip;
Public RegularExpressionValidator valzip;

protected override void OnLoad (EventArgs e) {
Lblzip.forecolor = Valzip.isvalid? Color.Black:Color.Red;
}
}

All of the above methods are perfect, but as long as you modify the validation as described above, you will find that unless you do the same thing on the client, it will look very inconsistent. The validation framework allows you to avoid many of these double effects, but you cannot avoid other effects that you must implement simultaneously on both the client and the server. The following is a fragment that performs the same task on the client computer:

<asp:label Id=lblzip Runat=server
text= "Zip Code:"/>
<asp:textbox Id=txtzip Runat=server
Onchange= "Txtziponchange ();"/></asp:textbox><br>
<asp:regularexpressionvalidator Id=valzip Runat=server
Controltovalidate=txtzip
Errormessage= "Invalid ZIP code"
Validationexpression= "[0-9]{5}"/><br>

<script language=javascript>
function Txtziponchange () {
If client authentication is not active, no action is performed
if (typeof (page_validators) = = "undefined") return;
Change the color of a label
LblZip.style.color = Valzip.isvalid? "Black": "Red";
}
</script>

Beta 1 Client API

For beta version 1, some functions that can be invoked from client script may cause other situations.

Table 4. Functions that are called from client script

Name Description
Validatorvalidate (Val) takes a client validator as input. Causes the validator to check its input and update its display.
Validatorenable (Val, enable) Gets a client validator and a Boolean value. Enable or disable the client validator. If disabled, the client validator is not evaluated and the client validator is always displayed as valid.
Validatorhookupcontrol (Control, Val) gets an input HTML element and a client validator. Modify or create a change event for the element to update the validator when it changes. This function is appropriate for custom validators that are based on multiple input values.


Its special purpose is to enable or disable the validator. If you want validation to take effect only in specific cases, you may need to change the activation state on both the server and the client, otherwise you will find that the user is unable to submit the page.

The following example adds a field that is validated only when a check box is unchecked.

public class Conditional:page {
Public HtmlInputCheckBox Chksameas;
Public RequiredFieldValidator rfvalshipaddress;
protected override void Validate () {
bool enableship =!chksameas.checked;
rfvalshipaddress.enabled = enableship;
Base. Validate ();
}
}

The following are the client-equivalent code:

<input Type=checkbox Runat=server Id=chksameas
Onclick= "Onchangesameas ();" > Same as payment address <br>
<script language=javascript>
function Onchangesameas () {
var enableship =!event.srcelement.status;
Validatorenable (rfvalshipaddress, enableship);
}
</script>


Validation rules and useful error messages

Each validator displays specific error messages about specific conditions for a particular control. There are some rules that confirm whether it is valid, and you may be somewhat confused as a developer, but these rules are necessary if you want to generate error messages that are actually helpful to the user.

All empty validators (except RequiredFieldValidator) are considered valid. If a null value is not valid, you typically need a requiredfieldvalidator and a different validator. You need to do this because, in general, you always want to display a different error message to the null validator and effectivity. You can also use ambiguous information, such as "You must enter a value, and the value must be between 1 and 10."

Another special rule that is used when the input field cannot be converted to the specified data type is related to CompareValidator and RangeValidator. The process of assessing the effectiveness of the CompareValidator that has been specified ControlToCompare is similar to the following:

Valid if the input field referenced by ControlToValidate is empty.
Invalid if the input field referenced by ControlToValidate cannot be converted to the desired data type.
Valid if the input field referenced by ControlToCompare cannot be converted to the desired data type.
The input field is converted to the desired data type and compared.
The third step seems to be somewhat counterintuitive. This is evaluated because it is difficult to write meaningful error messages for the validator if the validator checks the validity of multiple fields at the same time. You should use a standalone validator to report an error condition in the ControlToCompare input field. RangeValidator work in a similar way, with maximum and minimum properties.


Functions of Enabled, Visible and Display properties

The difference between the Enabled, Visible, and Display properties of the validator may not be very obvious.

Display=none can be used to specify that the validator does not display anything directly, but still evaluates it, still affects overall effectiveness, and can still place errors in the summary on both the client and the server. For client-side validation, these values determine whether the validator is turned on or off using the visibility style attribute or using the display style attribute. For server-side validation, display=dynamic indicates that no content is displayed when the input is valid, and display=static indicates that a blank space ("") appears without a newline. The last setting is used so that cells that contain only validators in the table are not collapsed to show nothing when they are valid.

Why not just use Visible=false to make the validator invisible? In asp+, the Visible property of a control has many meanings: the Visible=false control is not processed at all to be displayed or displayed. It is precisely because of this meaning that the visible=false of the validator means that not only nothing is displayed, but it cannot be used. This validator is not evaluated, does not affect the validity of the page, and does not place the error in the summary.

Enabled is neutral. For most cases, the effect of Enabled=false and Visible=false is exactly the same. In Beta 1 or later, there is an important difference: In client-side validation, a disabled validator is still sent to the browser, but is disabled. You can use the Validatorenable function in client script to activate the validator.

When using Visible or Enabled control for validation, be aware of the order of events on the above servers. Either make a change before validating it or verify it after the change. Otherwise, their IsValid values do not reflect the changes to the property.


CustomValidator control

The easiest way to extend the validation framework is to use the CustomValidator control. The control can be used to perform validation that cannot be performed by other validation controls, or to perform authentication that requires access to information on the server, such as a database or WEB service.

If you add a CustomValidator that defines only one server validation function, you will notice that the validator does not participate in client-side validation. When users switch between fields by using the TAB key, CustomValidator is not updated and requires a roundtrip server to perform its validation. If you want to use CustomValidator to perform a check that does not require information on any server, you can also use the ClientValidationFunction property to have the validator fully participate in client-side validation. Suppose you provide a clientvalidationfunction, ideally, you should perform the exact same check as the server authentication handler. In practice, however, only part of the validation is performed. The client-side validation function does not exceed the validation performed on the server because it is easy for the hacker to bypass the validation function.

The following is a simple example of using CustomValidator on both the client and the server to check if the input is even. The following describes the server functions (in C #):

public bool Servervalidation (object source, string value) {
try {
int i = Int. FromString (value);
Return ((i% 2) = = 0);
catch {
return false;
}
}

Here's how the function is declared on the client and a client-side validation function that performs the same check. This is usually a JScript form, but if your goal is microsoft®internet Explorer, you can also use the vbscript® form.

<asp:customvalidator id= "CustomVal2" Runat=server
Errormessage= "Number can not be removed by 2!" "
Controltovalidate= "Txtcustomdata"
Onservervalidationfunction=servervalidation
clientvalidationfunction= "Checkeven"/><br>
Data Field: <asp:textbox id= "Txtcustomdata" runat= "Server"/>
<script language=javascript>
<!--
function Checkeven (source, value) {
var val = parseint (value, 10);
if (isNaN (val))
return false;
Return ((val% 2) = = 0);
}
-->
</script>

Here are some considerations for using CustomValidator:

Similar to all other validation controls (except RequiredFieldValidator), CustomValidator is considered valid if the input field is blank.
If you use an older browser, or if you turn off client authentication, you will not be able to invoke the client validation function. Before you define this function, you do not have to check the functionality of the browser you are using, but you need to make sure that the browser does not cause scripting errors because of the definition. Be sure to make your client code an HTML annotation, as shown in the following example.
Two parameters are passed to your client function, corresponding to the arguments passed to the server function. The first is the client validator element, and the second is the control value specified by ControlToValidate. On the client, however, you can choose not to define parameters for the function, which will work as well.
If you use the BETA1 version or later, you can leave ControlToValidate blank. In this mode, the server function is always triggered once per round trip, and the client function always triggers once every attempt to commit. You can use this attribute to validate controls that other methods cannot validate, such as CheckBoxList or a separate radio button. Use this method if the condition is based on multiple controls, and you do not want the user to evaluate the condition by using the TAB key to switch between the fields on the page.
Another option in beta version 1 or later is the change event that hooks multiple controls. The method is to add some inline scripts that call the client function Validatorhookupcontrol, as described above.

Which controls can be validated?

To enable a control to be referenced by a validation control, the control must have a validation property. All controls that can be validated have the ValidationPropertyAttribute property, which indicates the properties that should be read when validating. If you write your own control, you can make the control participate in validation by providing one of the attributes to specify the property to use.

For the validation to work correctly on the client, the property must correspond to the value attribute of the HTML element that is displayed by the client. Many complex controls, such as DataGrid and Calendar, have no value on the client and can only be validated on the server. Therefore, only controls closest to the HTML element can participate in validation. In addition, the control must have a single logical value on the client. Therefore, RadioButtonList can be validated, but CheckBoxList is not possible.


End

The above explanation of asp+ validation may be beyond what you need to know. Enjoy it!



Related Article

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.