开发者

Assuming success or failure - are there benefits?

开发者 https://www.devze.com 2023-03-05 11:32 出处:网络
I\'m in the process of writing a simple form validation script, and wondered whether it\'s better practice (both in the scope of this script, and in general programming) to assume a success and test f

I'm in the process of writing a simple form validation script, and wondered whether it's better practice (both in the scope of this script, and in general programming) to assume a success and test for failure, or whether it's best to assume failure, then try to ensure each item is successful.

I've searched on the subject, only to be hit with a bunch of inspirational quotes, and am rather interested if there's a case where it will make a difference and as such, if one method is better/more secure/more efficient then the other?

Currently I test in a manner like this:

validat开发者_运维技巧ion = true

for each field
{
    if not validate(field)
    then validation = false
}

return validation

The only benefit I see in this particular case, is in the instance where there are no things to validate, the form submits.


With only a cursory exploration of the problem, I think the question boils down to whether it's optimal to your design to include or exclude data by default.

Assuming a collection of values A, B and C, there are two possible criteria for the result to be accepted: 1. all values must be valid, or 2. no values must be invalid.

In the first case, one would begin with the premise that the default result would be false until all values were validated and in the second, the default would be true until proved false by one invalid value.

To illustrate, assume a form containing:

First Name: [  ] (required)
Last  Name: [  ] (required)
Tel Number: [  ] (required)
Email Addr: [  ]

where the possible validations might be:

First Name must not be empty and must contain alpha chars only.
Last  Name must not be empty and must contain alpha chars only.
Tel Number must not be empty, must contain numbers only, formatted as (xxx) xxx-xxxx.
Email Addr if not empty, must be formatted as xxx@xxx.yyy, etc.

This case is inclusive in that all validation rules must return true for the input to be acceptable. Thus the default value should be false until proven true.

Now consider this partial form for sending an email message:

Subject:  [  ]
CC:       [  ]
BCC:      [  ]
Priority: [  ]

Since all fields are optional, this is the exclusive case where it would make sense to start with the assumption that the data are valid until they are proven invalid by one unacceptable value.

0

精彩评论

暂无评论...
验证码 换一张
取 消