In Semantic UI, I already know that you can validate forms, but there are only certain rules you can validate. In my signup form (in my application), I want to check if a user with a certain email already exists in the server. If the email exists, the user cannot signup with that certain email. How would I achieve this?
You can add custom validation rules to your form.
$.fn.form.settings.rules.myCustomRule = function(param) {
// Your validation condition goes here
return (param <= 10 )? true : false;
}
To pass parameters to a rule, use bracket notation in your settings object.
rules: [
{
type : 'myCustomRule[param]',
prompt : 'Custom Error'
}
]
Here is the doc Adding custom validation rule in semantic
Related
I have a plugin with a form where User can register, to avoid duplicate registrations I've added a custom Validator which checks if a FE user already contain the email.
//This is just the isValid method of the custom validator..
public function isValid($value): void
{
$existingUser = $this->frontendUserRepository->findByEmail($value)->getFirst();
if ($existingUser != null) {
$this->addError(
'E-mail already registered',
1592556619
);
}
}
Because of an additional double opt-in mechanism I would like to disable the new created FE user (which is created in the submit action of the registration form), so far so good.
But now my custom validator didn't find users which are disabled when try to find it by email.
So my question is, how can I tell it that he have to ignore the disabled state of the entry.
You will need to configure your repository method to ignore the disabled enable field. (See enablecolumns in TCA.)
You will need to add a custom findOneByEmail() method to your repository and configure the query accordingly:
$query = $this->createQuery();
$query->getQuerySettings()
->setIgnoreEnableFields(true)
->setEnableFieldsToBeIgnored(['disabled']);
Afterwards you can execute the query as usual which will now include disabled users:
$query
->matching($query->equals('email', $email))
->setLimit(1);
return $query->execute()->getFirst();
Notice that you should put this in a separate findOneByEmailIncludingHidden() or similar to avoid unexpected side-effects and make the special behavior of this query method clear.
(You may have noticed that findOneBy* is used here instead of findBy* since that will automatically return the first object.)
I do have a registration form in my laravel 5.4 application and laravel form request validation is used for server side validation. Some fields in this form are populated dynamically using calculations in javascript which need to be validated against user inputs.
The user input fields in the form are 'quantity', 'rate' and 'discount'.
The populated fields are 'total' and 'bill_amount'.
What i need to validate are :
Check 'total' equal to 'quantity' * 'rate'.
Check 'bill_amount' equal to 'total' - 'rate'
I would prefer laravel form request validation methods for this validation. I have tried to use methods like After Hooks and conditionally adding rule etc. and failed.
In simple words the requirement is : check if a field is equal to product of other two fields, and invalidate if not equal and validate if equal.(using form request validation.)
Thanks in advance!
After a long time I was able to find this solution.
Form request After Hooks can be used to achieve the result:
[I was unable to find this logic before]
public function withValidator($validator)
{
$quanty = $this->request->get("quantity");
$rate = $this->request->get("rate");
$billAmount = $this->request->get("bill_amount");
$validator->after(function ($validator) {
if(($quanty * $rate) != $billAmount) {
$validator->errors()->add('bill_amount', 'Something went wrong with this field!');
}
});
}
I'm creating a form with Angular2 and I created two custom validators for email address field.
The first validator checks for email validity, the second (async) validator checks if email address already exists on database.
In addition I would like to add a third validator for another verification.
Here is my code:
'email': ['', [validateEmail(), thirdValidator()], asyncValidator]
The behaviour that I want is the following:
Only when the first validator validates the control, the second validator should start. And only when the second validator terminates then the third validator can start its validation.
How to reach this?
Validators.compose method should do the job, example:
let formControls = {
'oldPassword': new FormControl({ value: ''}),
'newPassword': new FormControl({ value: ''}, Validators.compose([customValidator1, customValidator2]), customAsyncValidator)
};
Composed validators work simultaneously, meaning we can have multiple errors on the control at the same time (each validator attaches its own error if validation failed). If we need to have only one error on the control at a time, we can 'chain' validators by checking the status of the previous validation before performing next one. Something like this:
let customValidator2 = (ctrl: FormControl): any => {
if(ctrl.hasError('customValidationError1')) {
// there is the error attached by customValidator1,
// skip executing customValidator2 (nullify its error)
return null;
}
let isInvalid = true; // some condition...
return isInvalid ? { customValidationError2: true } : null;
}
This way we can accomplish 'ordering' the validators by their priority for example.
$crud->set_rules('user_password', 'Password', 'trim|required|matches[konfirmpass]');
$crud->set_rules('konfirmpass', 'Konfirmasi Password', 'trim|required');
$crud->callback_edit_field('user_password',array($this,'_user_edit'));
$crud->callback_add_field('user_password',array($this,'_user_edit'));
callback function:
function _user_edit(){
return '<input type="password" name="user_password"/> Confirmation password* : <input type="password" name="konfirmpass"/>';
}
My question is how to update if only "password" not blank?
I've installed CI 2.0.3 and GC 1.1.4 to test because at a glance your code looked fine. As it turns out, it is and your code works. I modified the out of the box employees_management method in the examples controller with GC. Added a user_password column to the database and added your code to the controller.
The code both ensures that the password fields match and that they're not empty when submit.
Empty results in "The Password field is required"
Mismatched results in "The Password field does not match the konfirmpass field."
Perhaps if this isn't working for you, you should post your entire method instead of just the rules and callbacks so we can see if there are any other problems.
Edit
To edit the field, only if the password has been edited you need to add
$crud->callback_before_update( array( $this,'update_password' ) );
function update_password( $post ) {
if( empty( $post['user_password'] ) ) {
unset($post['user_password'], $post['konfirmpass']);
}
return $post;
}
This however may mean that you need to remove the validation for empty password depending on which order the callbacks run (if they're before or after the form validation runs). If they run before the form validation, you'll need to also need to run a call to callback_before_insert() and add your validation rules within the two callbacks. Insert obviously will need the required rule, and update won't.
Edit 2, Clarification of Edit 1
Having looked into it, the validation runs before the callbacks, so you can't set validation rules in the callback functions. To achieve this you'll need to use a function called getState() which allows you to add logic based on the action being performed by the CRUD.
In this case, we only want to make the password field required when we are adding a row, and not required when updating.
So in addition to the above callback update_password(), you will need to wrap your form validation rules in a state check.
if( $crud->getState() == 'insert_validation' ) {
$crud->set_rules('user_password', 'Password', 'trim|required|matches[konfirmpass]');
$crud->set_rules('konfirmpass', 'Konfirmasi Password', 'trim|required');
}
This will add the validation options if the CRUD is inserting.
I have a registration form with about 30 fields (yes.. I know.. insanity). I need some of these fields to be required by certain types of people. What I'd like to do is just use a query string like example.com/user/register/?type=notrequired. If type = notrequired then I'd like to make to make the fields not required. Is this possible? I tried using the jQuery Validate plugin but its not working.. I'm thinking the built in Drupal validation is conflicting with it :(
The required flag is set server side so I doubt you'll be able to affect it using javascript. You'll have to hook into the form and make the changes in PHP, something like this in a custom module:
function mymodule_form_user_register_form_alter(&$form, &$form_state, $form_id) {
if (isset($_GET['element_name']) && $_GET['element_name'] == 'notrequired') {
$form['element_name']['#required'] = FALSE;
}
}
Hope that helps