How to use email validation inside a custom validation function? - php

I have created a custom validation function. Now I want to validate email inside that function, how can I do that?
Below is my code:
public function rules()
{
return [
['email', 'filter', 'filter' => 'trim'],
['email', 'required'],
['email', 'validateEmail'],
];
}
public function validateEmail($attribute, $params) {
if(ctype_digit($this->email)){
if(strlen($this->email)!=10)
$this->addError($attribute,'Phone number should be of 10 digits');
else{// Email validation using emailvalidator.}
}
}

You can call the email validator directly. The message is the error message that will be added to the model when validateAttribute is used. If you want to use the default error message you can leave it out:
public function validateEmail($attribute, $params) {
...
else {
$emailValidator = new \yii\validators\EmailValidator();
$emailValidator->message = "Invalid Email";
$emailValidator->validateAttribute($this, $attribute));
}
}

Related

How to change the default message in Respect Validation?

I use Respect Validation for password matches on a Slim app:
class PasswordController extends Controller
{
;
;
public function postChangePassword($request, $response) {
$validation = $this->validator->validate($request, [
'password_old' => v::noWhitespace()->notEmpty()->matchesPassword($this->auth->user()->password),
'password' => v::noWhitespace()->notEmpty()
]);
if($validation->failed()) {
// stay on the same page
}
die('update password');
}
}
I can authenticate the password:
class MatchesPassword extends AbstractRule
{
protected $password;
public function __construct($password) {
$this->password = $password;
}
public function validate($input) {
// compare the non-hashed input with the already hashed password
}
}
...and I created my own custom string for the 3rd rule ('password_old'):
class MatchesPasswordException extends ValidationException
{
public static $defaultTemplates = [
self::MODE_DEFAULT => [
self::STANDARD => 'Password does not match.',
],
];
}
The script works fine, I get the following message when I submit with 'password_old' field empty:
"Password_old must not be empty"
I would like to change the above default message to a custom string, e.g.:
"The value must not be empty"
You can overwrite the messages using the findMessages method of ValidationException and using assert:
try {
v::noWhitespace()->notEmpty()->matchesPassword($this->auth->user()->password)->assert($request->getParam('password_old'));
v::noWhitespace()->notEmpty()->assert($request->getParam('password'));
} catch (ValidationException $exception) {
$errors = $exception->findMessages([
'notEmpty' => 'The value must not be empty'
]);
print_r($errors);
}

Could not find validation handler checkCurrentPassword for current_password

I am getting error like this
Warning (512): Could not find validation handler checkCurrentPassword
for current_password
[CORE/Cake/Model/Validator/CakeValidationRule.php, line 281]
my User.php
public function validate_passwords() {
return check( $this->data[$this->alias]['confirm_password'], $this->data[$this->alias]['password']);
}
You can not access check() like this beacause it is a protected method
for more info see : http://api.cakephp.org/3.0/class-Cake.Validation.Validation.html
don't you try something like below :
public function validate_passwords() {
return array('check' => array($this->data[$this->alias]['confirm_password'], $this->data[$this->alias]['password']));
}
To validate confirm_password with password add this rule:
$validator->add('confirm_password', 'no-misspelling', [
'rule' => ['compareWith', 'password'],
'message' => 'Passwords are not equal',
]);
you can use this for validate confirm_password with password
public function validate_passwords()
{
return $this->data[$this->alias]['password'] === $this->data[$this->alias]['confirm_password'];
}
its work for you.

How to create custom validation within the same controller?

I have a form which performs the inserting function, the related method is :
public function addthread(Request $request) {
//validate
$this->validate($request, [
'title' => 'required|unique:thread|max:255',
'num_opt' => $this->checkOpt($request),
]);
}
I want to use a custom function to validate the num_opt elements,:
protected function checkOpt($request, Validator $validator) {
//$num_opt = $request->input('num_opt');
if ($request->has('$num_opt')) {
//$validator->errors()->add ??
How to customize the error message?
}
//die();
}
Questions:
Is the above code practice is wrong or not?
How can I access $validator and customize the error message in the checkOpt function?

Numeric Custom validation Message in Laravel 5.2

I am writing the following code server side to validate if the role is selected or not ...
public function rules()
{
return [
'RoleID' => 'required|integer|min:1',
];
}
public function messages() {
return [
'User.RoleID' => 'Please select role.',
];
}
Current Message
The role i d must be at least 1.
Expected Message
Please select role.
Can you please guide me to right path?
try this
public function messages () {
return [
'RoleID.min' => 'Please select role.',
];
}

Codeigniter form validation error message

I have a form on my website header where i allow the user to log in with his username/password... then i POST to /signin page and check if the username exists to allow the user to log in.. if there is a problem upon login i output these errors...
i tried using the following code to show a custom error but with no luck
if ($this->form_validation->run() == false){
$this->load->view("login/index", $data);
}else{
$return = $this->_submitLogin();
if ($return == true){
//success
}else{
$this->form_validation->set_message('new_error', 'error goes here');
//error
}
$this->load->view("login/index", $data);
}
how does set_message work and if this is the wrong method, which one allow me to show a custom error in this case?
EDIT :
validation rules:
private $validation_rules = array(
array(
'field' => 'username',
'label' => 'Username',
'rules' => 'trim|required|callback__check_valid_username|min_length[6]|max_length[20]|xss_clean'
),
array(
'field' => 'password',
'label' => 'Password',
'rules' => 'trim|required|min_length[6]|max_length[32]'
),
);
The set_message method allows you to set your own error messages on the fly. But one thing you should notice is that the key name has to match the function name that it corresponds to.
If you need to modify your custom rule, which is _check_valid_username, you can do so by perform set_message within this function:
function _check_valid_username($str)
{
// Your validation code
// ...
// Put this in condition where you want to return FALSE
$this->form_validation->set_message('_check_valid_username', 'Error Message');
//
}
If you want to change the default error message for a specific rule, you can do so by invoking set_message with the first parameter as the rule name and the second parameter as your custom error. E.g., if you want to change the required error :
$this->form_validation->set_message('required', 'Oops this %s is required');
If by any chance you need to change the language instead of the error statement itself, create your own form_validation_lang.php and put it into the proper language folder inside your system language directory.
As you can see here, you can display the custom error in your view in the following way:
<?php echo form_error('new_error'); ?>
PS: If this isn't your problem, post your corresponding view code and any other error message that you're getting.
The problem is that your form is already validated in your IF part! You can fix the problem by this way:
if ($this->form_validation->run() == false){
$this->load->view("login/index", $data);
}else{
$return = $this->_submitLogin();
if ($return == true){
//success
}else{
$data['error'] = 'Your error message here';
//error
}
$this->load->view("login/index", $data);
}
In the view:
echo $error;
The CI way to check user credentials is to use callbacks:
$this->form_validation->set_rules('username', 'Username', 'callback_username_check');
...
public function username_check($str) {
// your code here
}
I recommend you to read CI documentation: http://codeigniter.com/user_guide/libraries/form_validation.html
The way I did this was to add another validation rule and run the validation again. That way, I could keep the validation error display in the view consistent.
The following code is an edited excerpt from my working code.
public function login() {
$this->form_validation->set_rules('email', 'Email', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
$data['content'] = 'login';
if($this->form_validation->run()) {
$sql = "select * from users where email = ? and password = ?";
$query = $this->db->query($sql, array($this->input->post('email'), $this->input->post('password')));
if($query->num_rows()==0) {
// user not found
$this->form_validation->set_rules('account', 'Account', 'callback__noaccount');
$this->form_validation->run();
$this->load->view('template', $data);
} else {
$this->session->set_userdata('userid', $query->id);
redirect('/home');
}
} else {
$this->load->view('template', $data);
}
}
public function _noaccount() {
$this->form_validation->set_message('_noaccount', 'Account must exist');
return FALSE;
}
Require Codeigniter 3.0
Using callback_ method;
class My_controller extends CI_Controller {
function __construct() {
parent::__construct();
$this->form_validation->set_message('date_control', '%s Date Special Error');
}
public function date_control($val, $field) { // for special validate
if (preg_match("/^[0-9]{2}.[0-9]{2}.[0-9]{4}$/", $val)) {
return true;
} else {
return false;
}
}
public function my_controller_test() {
if ($this->input->post()) {
$this->form_validation->set_rules('date_field', 'Date Field', 'trim|callback_date_control[date_field]|xss_clean');
if ($this->form_validation->run() == FALSE) {
$data['errors']=validation_errors();
$this->load->view('my_view',$data);
}
}
}
}
Result:
if date = '14.07.2017' no error
if date = '14-7-2017' Date Field Date Special Error

Categories