Класс Validator для валидации POST данных. Класс Validator для валидации POST данных Безобидный validation php

Доброго всем вечера (скорее ночи – прим.ред.). Сегодня мы будем немного совершенствовать ту . Для начала научимся делать проверку формы на php и сделаем некоторые манипуляции по защите .

Итак, смотрим на код ниже и отмечаем для себя следующие изменения и следующие причины изменений. Все новые строки я выделил цветом.

Изменено название полей формы . Вы спросите – на кой хрен нам это надо? А всё просто, отвечу я вам. Насколько мне известно, то некоторые спам боты рыскают по сайтам в поисках форм, и заполняют их, ориентируясь на названия этих полей. По идее если они не находят совпадений, то уходят восвояси, чего нам и надо. Конечно степень этой защиты не думаю, что особо велик, но от нас не убудет, а если писем спама уменьшится на 1 письмо, это уже будет хорошо=).

Проверка на правильность ввода адреса почты . В 17 строке используется оператор elseif, который будет проверяться, если if вернул нам положительный ответ, то есть сказал, что адрес почты вообще отсутствует, то есть не был введён. Здесь мы используем функцию preg_match, которая позволяет сравнить введённый адрес с регулярным выражением . Про регулярные выражения возможно я напишу кратко потом, а пока стоит знать, что регулярное выражение создаёт некий шаблон, с которым сверяется наша строка. И если, в нашем случае, введённый адрес не совпадает с выражением, то опять же будет выведена ошибка. Для примера вот ещё парочку регулярных выражений:
|^[-а-яе\s\.,;:\?!]+$|i – это регулярное выражение позволяет использовать только русский алфавит и некоторые символы типа пробела, точки, запятой и пр.
#http://[-a-z0-9_.]+[-a-z0-9_:@&?=+,.!/~*’%$]*\.(html?|php)#i – а это выражение позволяет проверить правильность написание адреса в интернете.

Далее используется оператор else, куда уже перенесён весь наш код по отправке письма. Правила проверки можно создать самому в любом количестве, просто дописывайте новые elseif, как например для проверки адреса почты, и будет вам счастье.




Контактное лицо:



Почта для связи:



Сообщение:






Вот так можно проверять ваши формы на PHP, не прибегая ни к чему постороннему. В следующий раз в посте на тему форм, думается мне, будет рассмотрена валидация форм на jQuery. А пока жду ваших комментариев и пожеланий. Всем спокойной ночи и весёлого утра=).

It is very essential to have the input to your form validated before taking the form submission data for further processing. When there are many fields in the form, the PHP validation script becomes too complex. Moreover, since you are doing the same or similar validation for most of the forms that you make, just too much of duplicate effort is spent on form validations.

About this generic PHP form validation script

This generic PHP form validator script makes it very easy to add validations to your form.

We create and associate a set of “validation descriptors” with each element in the form. The “validation descriptor” is a string specifying the type of validation to be performed. For example, “req” means required, “alpha” means allow only alphabetic characters and so on.

Each field in the form can have zero, one or more validations. For example, the input should not be empty, should be less than 25 chars, should be alpha-numeric, etc

You can associate a set of validation descriptors for each input field in the form.

Download the PHP form validation script

You can download the PHP form validation script below:
The zip file contains the form validation script formvalidator.php, documentation and usage samples.

Using the PHP form validation script
  • Include formvalidator.php in your form processing script
  • require_once "formvalidator.php"
  • Create a FormValidator object and add the form validation descriptors.
  • $validator = new FormValidator(); $validator->addValidation("Name","req","Please fill in Name"); $validator->addValidation("Email","email", "The input for Email should be a valid email value"); $validator->addValidation("Email","req","Please fill in Email");

    The first argument is the name of the input field in the form. The second argument is the validation descriptor that tells the type of the validation required. The third argument is the error message to be displayed if the validation fails.

  • Validate the form by calling ValidateForm() function
  • if(!$validator->ValidateForm()) { echo "Validation Errors:"; $error_hash = $validator->GetErrors(); foreach($error_hash as $inpname => $inp_err) { echo "

    $inpname: $inp_err

    \n"; } } Example

    The example below will make the idea clearer

    Name: Email:

    Adding Custom Validation

    If you want to add a custom validation, which is not provided by the validation descriptors, you can do so. Here are the steps:

  • Create a class for the custom validation and override the DoValidate() function
  • class MyValidator extends CustomValidator { function DoValidate(&$formars,&$error_hash) { if(stristr($formars["Comments"],"http://")) { $error_hash["Comments"]="No URLs allowed in comments"; return false; } return true; } }

  • Add the custom validation object
  • $validator = new FormValidator(); $validator->addValidation("Name","req","Please fill in Name"); $validator->addValidation("Email","email", "The input for Email should be a valid email value"); $validator->addValidation("Email","req","Please fill in Email"); $custom_validator = new MyValidator(); $validator->AddCustomValidator($custom_validator);

    The custom validation function will be called automatically after other validations.

    Table of Validation Descriptors

    Here is the list of all validation descriptors:

    Validation Descriptor Usage
    req The field should not be empty
    maxlen=??? checks the length entered data to the maximum. For example, if the maximum size permitted is 25, give the validation descriptor as “maxlen=25”
    minlen=??? checks the length of the entered string to the required minimum. example “minlen=5”
    alnum Check the data if it contains any other characters other than alphabetic or numeric characters
    alnum_s Allows only alphabetic, numeric and space characters
    num Check numeric data
    alpha Check alphabetic data.
    alpha_s Check alphabetic data and allow spaces.
    email The field is an email field and verify the validity of the data.
    lt=???
    lessthan=???
    Verify the data to be less than the value passed. Valid only for numeric fields.
    example: if the value should be less than 1000 give validation description as “lt=1000”
    gt=???
    greaterthan=???
    Verify the data to be greater than the value passed. Valid only for numeric fields.
    example: if the value should be greater than 10 give validation description as “gt=10”
    regexp=??? Check with a regular expression the value should match the regular expression.
    example: “regexp=^{1,20}$” allow up to 20 alphabetic characters.
    dontselect=?? This validation descriptor is for select input items (lists) Normally, the select list boxes will have one item saying ‘Select One’. The user should select an option other than this option. If the value of this option is ‘Select One’, the validation description should be “dontselect=Select One”
    dontselectchk This validation descriptor is for check boxes. The user should not select the given check box. Provide the value of the check box instead of ??
    For example, dontselectchk=on
    shouldselchk This validation descriptor is for check boxes. The user should select the given check box. Provide the value of the check box instead of ??
    For example, shouldselchk=on
    dontselectradio This validation descriptor is for radio buttons. The user should not select the given radio button. Provide the value of the radio button instead of ??
    For example, dontselectradio=NO
    selectradio This validation descriptor is for radio buttons. The user should select the given radio button. Provide the value of the radio button instead of ??
    For example, selectradio=yes
    selmin=?? Select atleast n number of check boxes from a check box group.
    For example: selmin=3
    selone Makes a radio group mandatory. The user should select atleast one item from the radio group.
    eqelmnt=??? compare two elements in the form and make sure the values are the same For example, ‘password’ and ‘confirm password’. Replace the ??? with the name of the other input element.
    For example: eqelmnt=confirm_pwd

    This and the next chapters show how to use PHP to validate form data.

    PHP Form Validation

    Think SECURITY when processing PHP forms!

    These pages will show how to process PHP forms with security in mind. Proper validation of form data is important to protect your form from hackers and spammers!

    The HTML form we will be working at in these chapters, contains various input fields: required and optional text fields, radio buttons, and a submit button:

    The validation rules for the form above are as follows:

    Field Validation Rules
    Name Required. + Must only contain letters and whitespace
    E-mail Required. + Must contain a valid email address (with @ and .)
    Website Optional. If present, it must contain a valid URL
    Comment Optional. Multi-line input field (textarea)
    Gender Required. Must select one

    First we will look at the plain HTML code for the form:

    Text Fields

    The name, email, and website fields are text input elements, and the comment field is a textarea. The HTML code looks like this:

    Name:
    E-mail:
    Website:
    Comment:

    Radio Buttons

    The gender fields are radio buttons and the HTML code looks like this:

    Gender:
    Female
    Male
    Other

    The Form Element

    The HTML code of the form looks like this: