Parameter verification prevents users from maliciously changing the difference value.

Source: Internet
Author: User
Tags string indexof

Reusable test functions
Verification is to determine the format of data that can be received by a specific input domain. Naturally, the requirements for many input domains are similar: for example, most input domains cannot be empty, and both the zip code and membership code can only contain numbers.

Therefore, we can solve the problem of data verification by writing reusable functions that meet various requirements. Our goal is to make these functions as generic as possible; then we demonstrate how to call them when they are needed.

Check your string
We start with the simplest functions, which are listed by code B. The notnull function is used to check whether the string it receives is null. The isblank function checks whether the string is composed of spaces. The issize function checks whether the string length meets the requirements.

Code B: Several string verification functions


Function notnull (STR ){
If (Str. Length = 0)
Return false
Else
Return true
}

Function notblank (STR ){
For (I = 0; I <Str. length; I ++ ){
If (Str. charat (I )! = "")
Return true
}
Return false
}

Function issize (STR, size ){
If (Str. Length = size)
Return true
Else
Return false
}
The notnull function checks whether there is any input in the text box. It calls the length method of string. If it is found that the length of the string passed to it is equal to zero, it considers the character to be null and returns false; otherwise, true is returned.

The method for checking whether a string is completely composed of spaces is somewhat different from the preceding principle, but it is basically similar. This is done by the notblank function. This function extracts every character in the string and checks whether it is a space. If no space character is found, true is returned. If only spaces are found, the function returns false.

The input data often requires a specific length. For example, the zip code should consist of eight or nine digits. In addition, the input format is incorrect. The length of a Member or member number should also be specific.

The issize function helps to verify this type of data. This function receives both the string to be checked and the expected String Length. Then, check whether the received length matches the actual length of the string. If yes, true is returned; otherwise, false is returned.

Process numbers
Users may enter other things where they need numbers. This is a common problem. If your application is dependent on this data for computing next, the problem becomes very serious. To solve this problem, we also provide the following three functions in our code library for verifying data: isdigits, isnumber, and isinrange. They are all listed in code C.

Code C: A function used to check numbers


Function isdigits (STR ){
VaR I
For (I = 0; I <Str. length; I ++ ){
Mychar = Str. charat (I)
If (mychar <"0" | mychar> "9 ")
Return false
}
Return true
}

Function isnumber (STR ){
Numdecs = 0
For (I = 0; I <Str. length; I ++ ){
Mychar = Str. charat (I)
If (mychar> = "0" & mychar <= "9") | mychar
= "."){
If (mychar = ".")
Numdecs ++
}
Else
Return false
}
If (numdecs> 1)
Return false
Return true
}

Function isinrange (STR, num1, num2 ){
VaR I = parseint (STR)
Return (I> = num1) & (I <= num2 ))

}

The isdigits function checks and ensures that the string is composed of digits. Here, the function also extracts each character from the string and checks whether they are out of the 0-9 range. If any character is not in this range, the function returns false; otherwise, the function returns true.

Suppose you have some USD or other data that can be expressed in decimal places. Such data contains a decimal point. In this case, the isdigits function cannot recognize them correctly. We need to identify whether a string is completely a number and contains at most one decimal point. The isnumber function can do this.

The isnumber function is a little complicated. It uses the opposite algorithm than isdigits. This function also extracts every character in the string, but does not check whether it is out of the 0-9 range, but whether it falls within this range. At the same time, it also checks whether the character is a decimal point. If yes, it will add a counting variable. If any character that does not match the preceding content is found during the check, the function returns false immediately. If the cycle ends, the function checks whether there are too many decimal points. If there are more than one decimal point, false is returned; otherwise, true is returned.

The isinrange function checks whether the string is within the specified number range. In addition to receiving the string to be checked, it also accepts two numbers, indicating the start value and end value of the given interval, respectively. This function first converts the received string to an integer using the string parseint method, and then checks whether the converted number is within the received range.

Small re-formatting

The isdigits and isnumber functions are good, but there are still some limitations. Sometimes, although the string character entered by the user is reasonable, it still cannot pass the verification or disrupt the next operation. For example, users may insert spaces or break numbers in the middle of the zip code, or add the dollar sign ($) before their dollar numbers ). There is no real error in the data at this time, but we only need to extract the numbers from the data.

Fortunately, there is a general solution: reformat the string and remove all irrelevant characters to get the expected number. Then we can check the length and range of the re-formatted string, and so on.

We provide two functions for reformatting: stripnondigits and stripchars, as shown in code D. The stripnondigits function extracts each character in the received string and sends it to isdigits. If the character is a number, stripnondigits adds it to a new string variable to create a string consisting of only digits. When the loop ends, the function returns the new character.

Code D: removes all non-numeric characters from a string.

Function stripnondigits (STR ){
VaR I
VaR newstring = ""
For (I = 0; I <Str. length; I ++ ){
Mychar = Str. charat (I)
If (isdigits (mychar ))
Newstring + = mychar
}
Return newstring
}

Function stripchars (STR, chars ){
VaR I
VaR newstring = ""
For (I = 0; I <Str. length; I ++ ){
Mychar = Str. charat (I)
If (chars. indexof (mychar) =-1)
Newstring + = mychar
}
Return newstring
}

On the other hand, the stripchars function is used to remove the specified character from the string. This function has two parameters: STR is the input string, and chars is the character string, which consists of the characters to be removed from the string. Use the string indexof method to check whether each character in the STR string is contained by chars. If not, this character is added to a new string. Note: If the substring to be searched is not in the parent string, the indexof method of string returns-1. When the function stops running, the new string is returned.

Step 2: Verify the input domain

The next step is to create a function to verify the input domain. This can be done in multiple ways. Regardless of the method used, there are two key points that must be kept in mind.

First, if the user inputs the error data, you should keep the focus on the current input domain and have the opportunity to correct the error. Do not let the user return to the correct error afterwards. Second, if a user makes a mistake, he or she should be prompted. The details of the prompt depend on the specific application.

Simple string Verification
We start with an input field that is not required except for a non-null string. This type of verification applies to the input of names, addresses, and city areas. We can create a common function to handle all these situations. This function is named validatestring, as listed in code E.

Code E: Check the string code


// Global variable set at start of script
VaR emptystring = "field is blank. Please enter"

Function validatestring (myfield, S ){
If (notnull (myfield. Value) & notblank (myfield. Value ))
Return true
Else {
Myfield. Focus ()
Alert ("the" + S + emptystring + S)
Return false
}
}

The validatestring function accepts two parameters: the first is a reference to the input field to be verified, and the other is a string used to indicate a user error. Note that this function relies on the reusable functions isnull and isblanks created in step 1 to complete the task. If neither of the two functions returns false, the validatestring function returns true.

Whenever an error occurs, the validatestring function takes three steps:

Keeping focus on the current input field gives users the opportunity to enter more appropriate data.
Provide you with an error message.
Returns false to the function that calls it.
The warning information displayed by the validatestring function is stored in a global variable emptystring, as shown in code E. At the beginning of the script, this string variable is assigned "field is blank. Please enter ". The validatestring function connects the string with the received string parameter S to form a warning message corresponding to the verified input field. For example, if we use the following statement to call validatestring:

Validatestring (Form. firstname, "first name ")

The string "first name" is passed to S. We can see the output prompt in Figure B.

Figure B

 

Verify numeric Input
The validatememnum and validatepledge functions are used to verify the number input, which is listed by code F. The first function validatememnum is used to verify our member # domain, which requires entering a number between 100 and 999. (This indicates that the site has a certain membership base .)

Code F: function used to verify the number input

 
Function validatememnum (myfield ){
If (isdigits (myfield. Value) & isinrange (myfield. Value, 100,999 ))
Return true

Else {
Myfield. Focus ()
Alert ("invalid customer number. Please enter a three digit number between 100 and 999 ")
Return false
}
}

Function validatepledge (myfield ){
If (notnull (myfield. Value )){
Newstring = stripchars (myfield. value, "$ ")
If (isnumber (newstring ))
Return true
Else {
Myfield. Focus ()
Alert ("invalid pledge amount. Please enter
Valid dollar amount .")
}
}
Return false
}

The validatememnum function also relies on the reusable functions we have previously created. (Have you summarized this mode ?) This function calls isdigits to check whether all input data is numbers, and then calls isinrange to check whether the number is between the second and third parameters. If these requirements are not met, the processing method of the function is similar to the validatestring we saw earlier.

Sometimes, in addition to verifying the integer, you also need to verify that the number of mortgaged US Dollars contains decimal points. We use the validatepledge function. In validatepledge, use stripchars to remove the dollar sign that the user may enter, and then call the isnumber function to check whether the input quantity is a reasonable integer or small value.

Abbreviated state name or zip code
Code G lists the code that verifies the zip code and the abbreviation of the State. The verification state abbreviation code illustrates how to validate input with limited options. If you enter few options to be selected (10 or less), you can use the selection element to save the trouble of verifying data. However, the abbreviations of 50 states will form a very bulky list, so we adopt other methods.

Code G: Verify continent and zip code

VaR statecodes = Al/AK/AZ/AR/CA/CO/ct/DE/DC/FL/GA/Hi/ID/
Il/In/IA/KS/La/ME/MD/MA/MI/Mn/MS/Mo/MT/nV/NH/nj/nm/NY/
NC/ND/OH/OK/or/pa/PR/RI/SC/TN/Tx/UT/VT/VA/WA/WV/wi/WY"

Function isstatecode (STR ){
VaR newstring = Str. touppercase ()
If (statecodes. indexof (newstring )! =-1 & Str. indexof ("/") =-1)
Return true
Else
Return false
}

Function validatestate (myfield ){
If (notnull (myfield. Value) & issize (myfield. Value, 2) & isstatecode (myfield. Value ))
Return true
Else {
Myfield. Focus ()
Alert ("invalid state code. Please enter 2-letter state postal abbreviation .")
Return false
}
}

Function validatezip (myfield ){
If (notnull (myfield. Value )){
Newstring = stripnondigits (myfield. value)
If (issize (newstring, 5) | issize (newstring, 9 ))
Return true
}
Myfield. Focus ()
Alert ("invalid zip code. Please enter 5-digit or 9-digit ZIP code .")
Return false
}

Because the input options are limited, we put these options into a global string variable named statecodes. The options are separated by a slash (/). The isstatecode function is used to check whether the input data can be found in the string statecodes.

This function first extracts the user input string and converts it to uppercase. In this way, no matter what format (either in upper or lower case) you enter, you can process the data in upper case. Then the function checks whether the input string can be found in statecodes.

If (statecodes. indexof (newstring )! =-1

Step 2 check to ensure that the user does not enter the separator we use ,/.

Str. indexof ("/") =-1)
Code G also lists the isstatecode functions called by validatestate. The validatestate function uses the notnull and issize functions to perform a basic check on the input string, and then calls isstatecode to ensure that the string is a reasonable input. If one of these tests fails, the function adopts the same processing method as the preceding test function.

The last function listed in Code G is used to check the zip code. Recall that the zip code consists of eight or nine digits. The first five digits and other digits may be separated by delimiters. We use the stripnondigits function to reformat the input string so that we can only pay attention to the entered number. After confirming that the input field is not empty, we remove all non-numeric characters and start to calculate whether the length of the input data conforms to the zip code length.

 

Step 3 and Step 3

Now, we have completed writing all the test functions. How can we use them for webpages?

Create a verification function library
First, because these functions are common, we hope to use them on as many pages as possible. A good way is to put them all in a javascript library file with. js as the extension. Any page that contains a reference to the file in the script block can access these functions. For example, we cut all the global variables and functions listed in code A into a text file named validate. JS, and then write the following code in the header block on any web page:

<Script language = "JavaScript" src = "Validate. js">
</SCRIPT>

In this way, we can call any function contained in the JS file on this page.

Obtain results
The code used to start the validation process is listed by code H. This function is placed in another script block on the page that contains our forms.

Code h: script block on the form page

<SCRIPT>
Function checkform (form ){
Return (validatestring (Form. firstname, "first name ")&&
Validatestring (Form. lastname, "Last Name ")&&
Validatememnum (Form. membernum, "member number ")&&
Validatestate (Form. State )&&
Validatezip(form.zip )&&
Validatepledge (Form. Pledge ))
}
</SCRIPT>

Let's look back at the code for creating a form contained in code A. The following statement indicates that clicking the sumbit button can trigger the running of the checkform function:

<Input type = "Submit" value = "Submit"
Onclick = "Return checkform (this. Form)" name = "Submit">

The function checkform accepts the form as a parameter, and then submits each input field in the form to the corresponding validation function for processing.

What are the results? Recall that if the event handler function of the submit button object returns false, the object will be unsubmitted. Therefore, if any of the verification functions called by checkform returns false, checkform returns false, and the form is not submitted. If all functions return true, the form that fills up the verified data will be submitted.

Finally, there is a piece of advice: the functions listed above can guide you to establish a hierarchical structure of the test function, and provide some skills for your data check work. They do not guarantee that all data verification needs are met, because the data you need to input varies.

 

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.