0
爲了驗證給定的字段,我寫了這樣的函數。請檢閱並提高我的功能將項目值得使用函數驗證字段的更好方法php
我場
try{
$message = 'First Name accepts keyboard characters only.';
doValidateField ($firstName, 'First Name', true, 100, '/^([a-zA-Z0-9._\- #,^&`~<>:[email protected]$(){}\"\';\*\[\]?%| \n \r \t]*)$/', $message);
} catch (Exception $e) {
$errorMessage = $e->getMessage();
echo $errorMessage;
}
功能
/*
* The following function is validates the fields
* @params unknown values $fieldValue, $fieldName, $required, $maxLength, $mask, $message
* @return tables rows $rowResponse
*/
function doValidateField($fieldValue, $fieldName, $required, $maxLength, $mask, $message) {
// Checking the required field is empty or not
if ($required) {
if (strlen ($fieldValue) <= 0) {
throw new Exception ($fieldName . " is required.");
}
}
// Check field length is not greater than allowed length
if (strlen ($fieldValue) > $maxLength) {
throw new Exception ($fieldName . " cannot be greater than " . $maxLength . " characters.");
}
// check if specified mask exists in the field
if (! (preg_match ($mask, $fieldValue))) {
throw new Exception ($message);
}
}
有什麼不起作用?或者,也許你正在尋找http://codereview.stackexchange.com? – deceze 2012-02-07 06:47:17
「更好」哪個意義?你能指出你在當前版本中看到了哪些問題嗎? – 2012-02-07 06:47:17
您應該編寫更多特定的函數(更小,更簡單的函數),如IsEmail(),IsStrLen()。所有你需要做的就是「循環」你所有的測試,並調用相應的小功能。 – djot 2012-02-07 06:51:35