麻豆官网首页入口

Validation

A programmer should consider that any a user makes may be incorrect and should plan arrangements for such unexpected actions. Using helps a programmer to ensure that any input is possible and sensible.

Validation applies rules to inputted data. If the data does not follow the rules, it is rejected, reducing the risk that incorrectly input data may crash a .

A programmer can build various types of validation into a program:

  • Range check - the input must fall within a specified range. This is usually applied to numbers and dates, but can apply to characters. For example, when making a payment to someone, the amount to be entered might be set to be greater than zero and not greater than the funds available.
  • Length check - the input must not be too long or too short. For example, a surname will require at least one letter, but is unlikely to require more than 40.
  • Presence check - a data value must be entered. For example, entering a quantity when placing an order.
  • Format check - the data must be in the correct format, such as entering a date in the format DD/MM/YYYY.
  • Type check - the data must be of a specified data type, such as an when specifying a quantity.

Many programs use one or more of these validation checks. For example, when signing up for a user account on a website, the validation might include:

  • presence check - a username must be entered
  • length check - a password must be at least eight characters long
  • range check - age restrictions may require the user's date of birth to be before a certain date
  • format check - the user's date of birth must be entered in the specified format
  • type check - the password may need to have a mixture of upper and lower case letters, a number and a special character

Validation does not ensure that the data entered is correct, just that it is possible and sensible. A user may accidentally enter a date of birth that is possible and sensible, but incorrect. The program has no way of knowing that the date has been entered incorrectly.

To get around this, many programs include verification checks - they repeat the entered data to the user and ask them to confirm if this data is correct. If the user confirms the data, the program then assumes it to be correct. This is an example of how planning the design of a program can help reduce errors.

Validation can be very simple. This program will until the user enters a correct response:

response = ""
while response != "y" and response != 'n'
     response = input("Do you want to proceed? y/n")
     response.lower
endwhile
print("Okay, let's continue...")