I am using Moodle 3.1+. I am trying to add a custom validation into profile edit. The field is a custom user profile field. I have created a function
function validYop($element_name,$element_value) {
$len = strlen($element_value);
// If the string is empty, then return false
if ($len == 0) { return false; }
$first_letter = $element_value{0};
$last_letter = $element_value{$len-1};
if ($first_letter == $last_letter) {
return true;
} else {
return false;
}
}
Then I have registered the rule using below code.
$mform->registerRule('same_firstandlast','function','validYop');
$mform->addRule('profile_field_YearOfPassing','The first and last letters must be the same', 'same_firstandlast');
But the code is not working. Please help
Related
I have this line of code that I want to apply to a login page. I want to restrict the login for only user with certain domain name like "#mycompany.com" no other user can register without having this domain.
But the problem is that I can't get it to work, it passes all domains I have tried and does not return to false
The codes are copied and paste from two different forumpages, one that has no rules for domains and the second code with rules for restricted domains ( from line "//validate tld")that I pasted in and edited. Where does it go wrong, at the moment I can't see where?
public static function validateUserEmail($user_email, $user_email_repeat)
{
if (empty($user_email)) {
Session::add('feedback_negative', Text::get('FEEDBACK_EMAIL_FIELD_EMPTY'));
return false;
}
if ($user_email !== $user_email_repeat)
{
Session::add('feedback_negative', Text::get('FEEDBACK_EMAIL_REPEAT_WRONG'));
return false;
}
// validate the email with PHP's internal filter
// side-fact: Max length seems to be 254 chars
// #see http://stackoverflow.com/questions/386294/what-is-the-maximum-length-of-a-valid-email-address
if (!filter_var($user_email, FILTER_VALIDATE_EMAIL)) {
//validate tld
$validTlds = str_replace(".", "\.", VALID_EMAIL_TLDS);
$validTlds = "\.".str_replace(",", "|\.", $validTlds);
//$validTlds = str_replace(",", "|\.", $validTlds);
$emailArr = explode("#", $user_email);
$emailTld = $emailArr[1];
if ($emailTld !== 'mycompany.com')
{
Session::add('feedback_negative', Text::get('FEEDBACK_EMAIL_DOES_NOT_FIT_DOMAIN'));
return false;
}
if (!preg_match('/^[-a-z0-9]+('.$validTlds.')\z/', strtolower($emailTld))) {
//check main domain here
$exValidTlds = explode(",", VALID_EMAIL_TLDS);
$exValidTlds = array_map('trim', $exValidTlds);
foreach($exValidTlds as $tld) {//if exist then
if(!strstr($emailTld, ".".$tld)) {
if($tld !== strrchr($emailTld, $tld)) {
Session::add('feedback_negative', Text::get('FEEDBACK_EMAIL_DOES_NOT_FIT_PATTERN'));
return false;
}
}
}
Session::add('feedback_negative', Text::get('FEEDBACK_EMAIL_DOES_NOT_FIT_PATTERN'));
return false;
}
}
return true;
}
This is the original code I started with and the validation of domain I added in later. All this validation domain code seems to be ignored...
public static function validateUserEmail($user_email, $user_email_repeat)
{
if (empty($user_email)) {
Session::add('feedback_negative', Text::get('FEEDBACK_EMAIL_FIELD_EMPTY'));
return false;
}
if ($user_email !== $user_email_repeat) {
Session::add('feedback_negative', Text::get('FEEDBACK_EMAIL_REPEAT_WRONG'));
return false;
}
// validate the email with PHP's internal filter
// side-fact: Max length seems to be 254 chars
// #see http://stackoverflow.com/questions/386294/what-is-the-maximum-length-of-a-valid-email-address
if (!filter_var($user_email, FILTER_VALIDATE_EMAIL)) {
Session::add('feedback_negative', Text::get('FEEDBACK_EMAIL_DOES_NOT_FIT_PATTERN'));
return false;
}
return true;
}
EDIT...
I finally made it to work and this is how, so far it is working for me... The goal is that I don't want other people outside the organisation to be able to log in to the website.
if (filter_var($user_email, FILTER_VALIDATE_EMAIL)) {
$server = strstr($user_email, '#');
if ($server !== '#mycompany.com') {
Session::add('feedback_negative', Text::get('FEEDBACK_EMAIL_DOES_NOT_FIT_PATTERN'));
return false;
}
}
Your not operator is on the wrong side of the variable. It should be like this...
if ($emailTld !== 'mycompany.com')
I am writing a method that uses POST variables posted by AJAX to add a user to a certain course in the database, but I can't get the callback to work correctly:
public function enroll()
{
$package = array();
$this->load->library('form_validation');
$this->form_validation->set_rules('course', 'Vak', 'required|callback_not_enrolled');
$fields = array("course");
if ($this->form_validation->run($this) === FALSE) {
$errors = array();
$success = array();
foreach ($fields as $field) {
$error = form_error($field);
if ($error !== "") {
$errors[$field] = $error;
} else {
$success[$field] = True;
}
}
$package["field_errors"] = $errors;
$package["field_success"] = $success;
$package["success"] = False;
} else {
$package["database"] = $this->course_model->enroll_user($this->data["user"], $this->input->post("course"));
$package["success"] = True;
}
echo json_encode($package);
}
I wrote the callback not_enrolled to check if the user is not already enrolled to the database. Note that I can't use is_unique because I have to test the combined uniqueness of two fields (so just one or two separate ones don't do the trick) and the id of the user is not included in the form (because it's part of the Code Igniter session).
The callback function:
public function _not_enrolled($course)
{
$exists = ($this->user->is_enrolled($course, $this->data["user_id"]) != False);
if ($exists != False) {
$this->form_validation->set_message("not_enrolled", "Already enrolled");
return False;
} else {
return True;
}
}
And finally the method is_enrolled from the model:
public function is_enrolled($course, $user=False) {
if($user==False){
$user = $this->data["user_id"];
}
$this->db->select()->from("course_participant")->where("user_id", $user)->where("course_id", $course);
$query = $this->db->get();
return($query->num_rows()>0);
}
Through a call to var_dump($this->_not_enrolled($existing_course_id)); I know that both the callback function and the method from the model work, as it correctly returned true.
When I var_dump the $package array or validation_errors() I don't get any validation errors except that it says Unable to access an error message corresponding to your field name Vak(not_enrolled).
I tried removing the initial _ from the function name but that gives me a Server Status 500 error.
I have another setup exactly like this, albeit other database calls, with a callback using the same syntax. This method works perfectly.
$crud = new grocery_CRUD();
$crud->set_table('generate_eblskyid');
$crud->set_rules('salt', 'Salt Code','callback_check_salt');
$output = $crud->render();
then in the call back function i did the following
function check_salt($str)
{
$salt = $_POST['salt'];
if($salt > 5)
{
$this->get_form_validation()->set_message('salt',"Salt value must be less then FIVE");
return FALSE;
}
}
When I go to add record if I give a salt value below five the is inserted successfully but when I give a value greater then five it says "An error has occurred in insert" without displaying my custom message.
What I am doing wrong ??
Your check_salt($str) function should be like this
function check_salt($str)
{
if($str > 5)
{
$this->form_validation->set_message('check_salt',"Salt value must be less then FIVE");
return false;
}else{
return true;
}
}
In set_message function, the callback function name 'check_salt' should be given, not the field name 'salt' This should solve your problem.
This was the only way that I found to makes this work using:
CI 3 and Grocery Crud 1.6.1
$crud->set_rules('name', 'Name', array(
'required',
array(
'company_check',
function ($str) {
$company = $this->Company_model->searchCompanyByName($str);
if (count($company) > 0) {
$this->form_validation->set_message('company_check', 'Error, The company already exist.');
return false;
} else {
return true;
}
}
)
));
Hope this help,
I am a newbee to yii and i am middle of something.
I have many forms in view page where i click on submit it check the fields and enter database.
But my question is if i have 5 different forms that need to check for validation and should stay in the same form which is entering another form.In the view page i kept active for li which it is redirects to the page which is active form. How should i stop redirecting to active page if the fields are empty and should stay in that particular page and check for validation.
IN the controller i have kept like this
if(isset($_POST['myform']))
{
$valid = true;
foreach($_POST as $p)
{
if($p == null)
{
$valid = false;
}
}
if($valid)
{
$model->save();
$this->render('mypage',array('model'=>$model,'model1'=>$model1,'model2'=>$model2,'model3'=>$model3,'model4'=>$model4));
}
}
$valid = true;
foreach($_POST as $p){
if($p == null){
$valid = false;
}
}
if($valid){
$model->save();
$this->redirect('yoururl');
}
Try this
if(isset($_POST['myform']))
{
if(count($_POST)==count(array_filter($_POST)))
{
$model->save();
$this->render('mypage',array('model'=>$model,'model1'=>$model1,'model2'=>$model2,'model3'=>$model3,'model4'=>$model4));
}
}
I did register form in with zend form
$password = new Zend_Form_Element_Password('password');
$password->setLabel($this->_translate->_("Password:"))
->setRequired(true)
->addValidator('stringLength', true, array(4, 32));
$confirmPassword = new Zend_Form_Element_Password('confirmpassword');
$confirmPassword->setLabel($this->_translate->_("Confirm Password:"))
->setRequired(true);
I control password and confirmpassword in controller. if password and confirmpassword don't match then add error message under confirmpassword textbox. how i do?
Override isValid in your form
/**
* Validate the form, check passwords.
*
* #param array $data
* #return boolean
*/
public function isValid($data) {
$valid = parent::isValid($data);
if ($this->getValue('password') !== $this->getValue('password2')) {
$valid = false;
$this->password2->addError('Passwords don\'t match.');
}
return $valid;
}
The concept basically boils down to adding a Zend_Validate_Identical validator to the 'confirmpassword' field, using the data from the $this->_request->getParam('password') to test against. I use a custom method on an extended Zend_Form to process the post data from all my forms, it isn't an exact solution for you, but perhaps my code from my "EditUser" form can point you in the right direction.
From the controller:
// $form is a MW_Form_EditUser.
if ($this->_request->isPost() && $form->process($this->_request->getPost()))
{
// successful form - redirect or whatever here
}
From the MW_Form_EditUser class:
public function process(array $data)
{
// gets a copy of the user we are editing
$user = $this->getEditable();
// checks to see if the user we are editing is ourself
$isSelf = ($user->id == MW_Auth::getInstance()->getUser()->id);
// if the new_pass field is non-empty, add validators for confirmation of password
if (!empty($data['new_pass']))
{
$this->new_pass2->setAllowEmpty(false)->addValidator(
new Zend_Validate_Identical($data['new_pass'])
);
if ($curpass = $this->current_password) $curpass->setAllowEmpty(false);
}
if ($this->delete && !empty($data["delete"])) {
$this->delete->setValue(true);
$user->delete();
return true;
}
if ($this->isValid($data))
{
/// saves the data to the user
$user->email = $this->email->getValue();
$user->name = $this->name->getValue();
if ($password = $this->new_pass->getValue()) $user->password = $password;
if (!$isSelf)
{
if ($this->super->getValue()) {
$user->setGroups(array(MW_Auth_Group_Super::getInstance()));
} else {
$user->setGroups(array(MW_Auth_Group_User::getInstance()));
}
}
$user->save();
return true;
}
return false;
}
//inside form
public function isValidPSW($data) {
$valid = parent::isValid($data);
if ($data['pswd'] !== $data['pswd2']) {
$valid = false;
$this->pswd->addError('Passwords don\'t match.');
}
return $valid;
}
Using Zend_Validate_Identical is a good solution for you by Zend. I will give you another choice. jQuery. When you are using Zend_Validate_Identical form will go to the server and server will validate it. If passwords are not same it will return an error message. If you use jQuery form will not go to the server unless passwords are same.