Input Validation Patterns
Table Limits
A small table can keep validation limits close to the code that applies them.
Table Limits
table_limits.c
#include <stdio.h>
int withinLimits(int minValue, int maxValue, int value) {
if (value < minValue) {
return 0;
}
if (value > maxValue) {
return 0;
}
return 1;
}
int main(void) {
int ruleIndex = ;
int value = 45;
int limits[3][2] = {
{0, 10},
{20, 60},
{70, 90}
};
int minValue = limits[ruleIndex][0];
int maxValue = limits[ruleIndex][1];
int ok = withinLimits(minValue, maxValue, value);
printf("ruleIndex=%d min=%d max=%d value=%d ok=%d\n", ruleIndex, minValue, maxValue, value, ok);
return 0;
}
#include <stdio.h>
int withinLimits(int minValue, int maxValue, int value) {
if (value < minValue) {
return 0;
}
if (value > maxValue) {
return 0;
}
return 1;
}
int main(void) {
int ruleIndex = ;
int value = 45;
int limits[3][2] = {
{0, 10},
{20, 60},
{70, 90}
};
int minValue = limits[ruleIndex][0];
int maxValue = limits[ruleIndex][1];
int ok = withinLimits(minValue, maxValue, value);
printf("ruleIndex=%d min=%d max=%d value=%d ok=%d\n", ruleIndex, minValue, maxValue, value, ok);
return 0;
}
#include <stdio.h>
int withinLimits(int minValue, int maxValue, int value) {
if (value < minValue) {
return 0;
}
if (value > maxValue) {
return 0;
}
return 1;
}
int main(void) {
int ruleIndex = ;
int value = 45;
int limits[3][2] = {
{0, 10},
{20, 60},
{70, 90}
};
int minValue = limits[ruleIndex][0];
int maxValue = limits[ruleIndex][1];
int ok = withinLimits(minValue, maxValue, value);
printf("ruleIndex=%d min=%d max=%d value=%d ok=%d\n", ruleIndex, minValue, maxValue, value, ok);
return 0;
}
rule table
Each row stores the minimum and maximum accepted by one validation rule.
selected rule
The selected row drives the same validation function without duplicating branches.