Answer the question
In order to leave comments, you need to log in
Yii2 how to properly validate email?
Started learning yii2. Doesn't validate email for existence. Here is the code:
sitecontroller.php
public function actionRegister()
{
$model = new RegisterForm();
$model->load(Yii::$app->request->post());
return $this->render('register', ['model' => $model]);
}
<?php
namespace app\models;
use yii\base\Model;
/**
* Description of RegisterForm
*
* @author kvonosan
*/
class RegisterForm extends Model{
public $login;
public $password;
public $email;
public $username;
public function rules() {
return [
[['login', 'password', 'email'], 'required'],
['email', 'email'],
['email', 'validateEmail', 'message'=>'Email already exists!'],
];
}
public function validateEmail($attribute, $params) {
$users = new users();
if ($users->EmailExist($this->email)) {
$this->addError('email', 'This email already exist.');
}
}
}
<?php
namespace app\models;
use Yii;
/**
* Description of users
*
* @author kvonosan
*/
class users
{
public function register($login, $password, $username, $email) {
if (empty($login) || empty($password) || empty($email)) {
return false;
}
if (empty($username)) {
$username = 'Аноним';
}
$sql = "INSERT INTO users (id, login, password, username, fotos, email)"
. "VALUES (NULL , :login, :password, :username, NULL , :email);";
$command = Yii::$app->db->createCommand($sql);
$result = $command->execute(array(':login' => $login, ':password' => $password,
':username' => $username, ':email' => $email));
Yii::trace("insert into execute return " . $result);
return true;
}
public function EmailExist($email) {
if (empty($email)) {
return true;
}
$sql = "SELECT COUNT(*) FROM users WHERE email=:email";
$command = Yii::$app->db->createCommand($sql);
$result = $command->execute(array(':email' => $email));
if ($result === 1) {
return true;
} else {
return false;
}
}
}
<?php
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
$this->title = 'Register';
?>
<div class="site-register">
<h1><?= Html::encode($this->title) ?></h1>
<div class="row">
<div class="col-lg-4">
<?php $form = ActiveForm::begin(['id' => 'register-form']) ?>
<?= $form->field($model, 'login')->textInput(['autofocus' => true]) ?>
<?= $form->field($model, 'password') ?>
<?= $form->field($model, 'email') ?>
<?= $form->field($model, 'username') ?>
<div class="form-group">
<?= Html::submitButton('Submit', ['class' => 'btn btn-primary', 'name' => 'register-button']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
</div>
</div>
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question