jQuery Validate, changing rules on the fly - jquery-validate

I have been setting up my jQuery Validate rules in Javascript much like in this article:
http://www.raymondcamden.com/index.cfm/2009/2/10/An-Introduction-to-jQuery-and-Form-Validation-2
I store the rules in a jsony object called validationRules, then I pass the rules when I invoke the Validate plugin:
$("#myForm").validate(validationRules);
Later, I'd like to programatically change values based on user interactions, like this:
validationRules.rules.Quantity.min=10;
even though the value is updated, Validate doesn't honor the new value. I also tried, re-invoking the plugin:
$("#myForm").validate(validationRules);
but that didn't help.
I can just talk directly to the plugin:
$("#Quantity").rules("add", {min: 10});
and it behaves as one would expect. So I will use that syntax to change rules on-the-fly, but could someone shed some light on how I can tell Validate to honor the updated rules in validationRules?

I had the same problem and I have spent a lot of time trying to solve it. Finally I find a trick in the Validation Plugin creator´s GitHub account:
var $form = $('#formId'),
newRules = {rules...},
newMessages = {messages...};
$.each(newRules , function(key, value) {
newRules [key] = $.validator.normalizeRule(value);
});
$.extend( $form.validate().settings.rules, newRules );
$.extend( $form.validate().settings.messages, newMessages );
I am not quite sure about the messages, I am using it right now and seems to work fine.
This is the link where you can read more about it:
https://github.com/jzaefferer/jquery-validation/issues/214

Related

how to use the expand parameter in Xrm.WebApi.retrieveRecord

I am using below scripts to get the reference entity from email entity. When the scripts was triggered, it prompts 'Could not find a property named 'new_queue' on type 'Microsoft.Dynamics.CRM.email''.
The reference entity's scheme name is new_queue, and I think the structure of the script is same as the guidance of microsoft knowledge article.
(https://learn.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-webapi/retrieverecord)
Can anybody point out what's wrong here?
Xrm.WebApi.retrieveRecord("email", '4884f79f-42f3-ea11-a815-000d3a44afcc', "?$select=subject&$expand=new_queue($select=queueid,name)").then(
function success(result) {
var toLookup = new Array();
toLookup[0] = new Object();
toLookup[0].id = result.queueid;
toLookup[0].entityType = "queue";
toLookup[0].name = result.name;
alert(result.name);
}, function (error) {
Xrm.Utility.alertDialog(error.message);
});
This issue is usually an outcome of case sensitive schema name, try new_Queue instead of new_queue. You can always verify this by checking in xml metadata.
Update:
I remember that the activity (email, task, appointment, etc) is special and little different. Make sure you download the metadata xml from Developer resources and check the correct navigation property. It should look like email_new_queue or new_queue_email
To know the correct navigation property name to use it in $expand:
Request the "Email" entity and Include the following header Prefer: odata.include-annotations="*".
In the response, you should find a field that looks something like:
"_new_queue_value#Microsoft.Dynamics.CRM.associatednavigationproperty": "????"
Use the name you'll find in the place of "????" in the $expand expression.

How to disable a Dynamics CRM field when the value changes without breaking save?

We have a two state field called Primary that is set to either yes or no. When the field is set to no, the user should be able to change it to yes. When the field is set to yes, it should be disabled, so the user can no longer change it.
We have code in the onload event that handles this; that works just fine. The challenging case is the one where a user changes the field from no to yes and then saves the form. This should lock the field so the user can't change it back to no. We attempted to solve this by putting the following code in onsave event:
export function onSave() {
var primaryControl = Xrm.Page.getControl(
d.ConstituentAffiliation.AttributeNames.Primary.toLowerCase());
if (primaryControl) {
if (primaryControl.getAttribute().getValue()) {
primaryControl.setDisabled(true);
}
else {
primaryControl.setDisabled(false);
}
}
}
This partly works. It does disable the field so it can no longer be changed. The save doesn't work, however, because Dynamics CRM appears not to send the values of disabled fields back to the server during the save, so the new value does not actually get saved.
Any ideas would be welcome. :)
It seems the following line solves my problem:
Xrm.Page.getAttribute(d.ConstituentAffiliation.AttributeNames.Primary
.toLowerCase()).setSubmitMode("always");
So the code now reads as follows:
export function onSave() {
var primaryControl = Xrm.Page.getControl( d.ConstituentAffiliation.AttributeNames.Primary.toLowerCase());
if (primaryControl) {
if (primaryControl.getAttribute().getValue()) {
Xrm.Page.getAttribute( d.ConstituentAffiliation.AttributeNames.Primary.toLowerCase() ).setSubmitMode("always");
primaryControl.setDisabled(true);
}
else {
primaryControl.setDisabled(false);
}
}
}
I should credit this blog which was very helpful: http://blogs.msdn.com/b/arpita/archive/2012/02/19/microsoft-dynamics-crm-2011-force-submit-on-a-disabled-field-or-read-only-field.aspx
Looks like you've solved it however I was curious. Have you tried using a Business Rule? This kind of basic functionality is what Business Rules in CRM 2015 can handle quite well.
For example something like this:-

Advanced Validation with Lithium PHP Framework

I'm building a pretty complex and dynamic form via the Lithium PHP framework.
I've got the form working and saving to MongoDB with little problem. But I am having trouble with validation.
Simple validations (such as checking if a field is not empty or is numeric) are working fine. But I have to do a few complex validations that rely on a number of fields in the form.
For example, I have a form where a user can enter a question and then enter an unlimited number of possible answers for this question. The field ID for each answer is listed such as "answer_1", "answer_2", "answer_3", etc. The user can add an unlimited number of answers. This happens via some fancy JavaScript that inserts extra elements to the form on the client side.
At the validation level, I want to make sure that every answer which was added is not null.
I would like to do this using the "traditional" Validator functionality built within Lithium. I am also doing this at the Model level, not the Controller level (note - I have a workaround to solve this on the Controller level, but would rather do it the "right" way at the Model)
The problem, as far as I can tell, is that you can only pass a single value to the validator rule. I just need to pass back ALL values in the form to the validator. If I could do that, I would be golden. The pseudo-code for what I'm looking to do looks like this:
Validator::add('CorrectTest', function(&$value, $format = null, array $options = array()) {
foreach ($_data as $key => $value) {
if (stristr($key, "answer_")) {
if ($value == "") {
return false;
}
}
}
return true;
});
This code doesn't work, because the $_data value is not present. If I could just figure out a way to get a fully-populated "$_data" object into the Validator function, I think I could get this to work.
Thanks in advance for the help
Take a look at what's inside $options. You should have a 'values' key in there that has all of the values from the form.
So try
$_data = $options['values'];

Turn off required field validation based on query string value?

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

Accessing data in kohana validation

i'll try and be as clear as possible.
I'm working on some form validation using the wonderful kohana framework. However i have come at a crossroads and not sure whether the way i have taken is a wise choice.
Basically, i have a date selector using several select boxes (i toyed with the idea of using javascript date pickers but the select boxes proved to be more suitable for my purpose) and a date field in a database. I wanted to concatenate these select boxes into the date field so it can be checked to make sure its valid.
protected $_rules = array(
'mydate' => array(
'not_empty' => NULL,
'date' => NULL,
),
);
Now to me, it makes most sense to include the validation in the model, since that's where the data layer is in the MVC pattern, so i decided to create some class attributes named $_rules, $_filters and $_callbacks, each set as protected and with my basic rules applied. And then a function in the model that sets up a validation object using these attributes and returning it to whatever controller is calling it, then the controller can just run the validation and the job is done.
My problem comes when i want to concat these select boxes, to me it makes most sense to make a custom filter and pass in the post data, but with the filters rules and callbacks being attributes, i can't add any variables to them. My current solution is to manually add the extra filter in when the validation setup function is being run something similar to this:
public function setupValid($post) {
$this->_filters['mydatefield'] = array(
'MyClass::MyConcat' => array($post);
);
//creates a validation object and adds all the filters rules and callbacks
}
But i don't feel this is the cleanest solution, i'm probably nit picking as the solution works the way i require it to. However i'm not sure whether a filter was ever intended to do such a thing as this, or whether this should be a callback as the callback has access to the array by default, but then again callbacks are called last, which would mean i couldn't apply any rules like, 'not_empty' (not important in this case since they are pre populated select boxes, but might be in another case)
So i guess my question is, am i using filters as they were intended to be used?
I hope i've managed to explain this clearly.
Thanks
you need to keep in mind that you should only validate fields inside the $_rules that are very important to your database or business logic.
so for example if you would try to setup other form somewhere else in your app or you would provide a restfull api for your app, validation of the field 'day_field_(that_doesnt_exists_in_the_database_and_is_used_to_privide_a_better_ux_in_this_one_form)' => array('not_empty' => NULL) will give you a hard time to do that.
so i suggest you to keep your $_rules like they are now and provide some logic to your values() method:
// MODEL:
public function values($values)
{
if ( ! empty($values['day']) && ! empty($values['month']) && ! empty($values['year']))
{
$values['mydate'] = $values['year'].'-'.$values['month'].'-'.$values['day'];
}
return parent::values($values);
}
// CONTROLLER:
if ($orm->values($form['form_array'])->check())
{
$orm->save();
}
else
{
$this->template->errors = $orm->validate()->errors('validation');
}

Resources