Unable to change minLength dynamically - javascript

I have a dropdown which has countries and in the same form on 2nd line I have ZipCode texbox. I want to limit the minLenght of the zipcode field dynamically. For example If US is slected zipcode should not be less than 5 and for other countries some other minLength Limit. My form uses a parsley validator
I wrote below function onChange event of my country dropdown
function setZipLimit() {
alert("in Zip limit" + document.getElementById("billingCountry").value);
if (document.getElementById("billingCountry").value == "US") {
alert("I am in US");
$('#billingForm').parsley('destroy');
$('#billingPostalCode').data('minlength', 3);
$('#billingForm').parsley();
} else {
$('#billingForm').parsley('destroy');
$('#billingPostalCode').data('minlength', 10);
$('#billingForm').parsley();
}
}
But this doesnt seem to be helping. Can you please help me?

You cant just edit the Attribute, because parsley.js initially Reads the form and gets its Values. Changing them Afterwards shouldnt have any Effect.
However you can use the Parsley.js API for Javascript functions to Edit the constraints. You already used them to destroy and Build Parsley. Parsley got the following Function:
$( '#field' ).parsley( 'updateConstraint', { minlength: 6 } );
There are also some with addConstraint and removeConstraint in the Documentation:
http://parsleyjs.org/documentation.html
If your Form gets more complex and you have several of those dynamic cases, i recommend to only Destroy and Rebuild specific Parts of your Form. The Reason is (from an issue I had recently):
If you Destroy Parsley, change some Fields, build Parsley and then Destroy it again because another if Statement takes place, your previous Changes get thrown away, because Build only reads the js inbetween the Destroy and Build and reads the Form.

Related

UnhandledPromiseRejectionWarning: Field was not found by text|CSS|XPath

I am very new to coding and I am stuck at a place where I am trying to add some text to a field. The code is written in Javascript and we use Puppeteer as a helper. When I try to click on the field with the same locator, it clicks just fine, even when clearing the field, it works fine. The only issue is happening when I am trying to fill the field, at that time it is not able to find that field with the locator specified, not sure what is going on there.
Here is the code and the run results. In the code, after the pause statement, it is failing.
// View Trial Level Form
clinicalTrialsDashboard.openATrialLevelForm(common.trialLevelFormEditAccess);
within(patientInteraction_po.fullPageModalHeader, () => {
I.dontSeeElement(patientInteraction_po.formSettingsBtn);
I.seeElement(patientInteraction_po.auditHistoryBtn);
I.dontSeeElement(patientInteraction_po.queryModeBtn);
I.dontSeeElement(patientInteraction_po.printBtn);
I.dontSeeElement(patientInteraction_po.investigatorFlagBtn);
I.seeElement(patientInteraction_po.closeForm);
I.seeElement(patientInteraction_po.saveForm);
I.dontSeeElement(patientInteraction_po.saveAndComplete);
//I.fullyClearField(patientInteraction_po.trialLevelFormInput);
I.pause();
I.fillThisField(patientInteraction_po.trialLevelFormInput, 'dddd');
I.waitClick(patientInteraction_po.saveForm);
I.waitForHideForLongTime(common_po.loadingSpinner);
I.see(common.alertMessage);
I.see('Trial Level Form Saved');
I.waitClick(common.okayBtn);
});
Result:
I.
I fill field {"css":".scheduled-form-display [data-c^="form-question"] [data-i*="input-element"]"}, "dddd"
(node:11479) UnhandledPromiseRejectionWarning: Field "{"css":".scheduled-form-display [data-c^="form-question"] [data-i*="input-element"]"}" was not found by text|CSS|XPath
Thanks.

Hiding a Section on Dynamics 365 using JS

I'm trying to take a field value (that's a two option check box) and if it is checked then set the visibility on a section to be true, and if it's not checked then to set the visibility to false. I have it set on the field to call the function on an on change event.
When I go into the form and either check the box or uncheck the box it gives me a script error.
This is the function I'm using:
function SetProductVisible(){
if (Xrm.Page.getAttribute("ee_productspecific").getValue()){
Xrm.Page.ui.tabs.get(“SubGrids”).sections.get(“Products”).setVisible(true);
}
else{
Xrm.Page.ui.tabs.get(“SubGrids”).sections.get(“Products”).setVisible(false);
}
};
Thank you for your help.
The fields default value is also set to "No"
Ensure that you are using the right quotation marks by replacing “ and ” with ".
As mentioned in the comments, also ensure that you are using the right name for your tab and section, and check the developer console for more information about the error.
here is your solution...
I created a new field on the CRM form called "log_showhide" which is a two option field. You need to edit the code below to match your Section name and field name with the correct values...
Furthermore, I would set the code to run on load of the form as well as on change of your field.
This method is applicable to Microsoft Dynamics 365 v9.x
function hideOrShow(executionContext){
var a = executionContext.getFormContext().getAttribute("log_showhide").getValue();
if (a == 0) {
Xrm.Page.ui.tabs.get("SUMMARY_TAB").sections.get("sampleSection").setVisible(true);
} else {
Xrm.Page.ui.tabs.get("SUMMARY_TAB").sections.get("sampleSection").setVisible(false);
}
}
Rather than doing a custom web resource to show/hide a field or section, I would recommend you go with a Business Rule. With a Business Rule you can set up a simple check of the value of one field and hide other fields based on that.
Another way to hide a section by field's parent. Just refer a field on that section:
function SetProductVisible()
{
var some_section = Xrm.Page.getControl("new_field_on_that_section_name").getParent();
some_section.setVisible(Xrm.Page.getAttribute("ee_productspecific").getValue());
};

Warn on non-ASCII Characters in Django Form

I'm trying to add some client-side Ajax validation of my Django form. I want to warn users, as they are typing in a field, if any of the characters they just inputted are not ascii.
I originally put the basic python to check for ascii characters in my form's clean method. I don't want to do that, though, as I don't want to produce an error but rather just give a warning message and let the user continue with the rest of the form.
try:
field_value.decode('ascii')
except UnicodeEncodeError:
#raise forms.ValidationError("Non-ASCII characters may cause issues in registering your data. Consider removing these characters. You may still submit at your own risk.")
# Just want to show a warning so the user can still submit the form if they wish
I want to show a small warning under the field as the user is typing. I've tried using django-dajax, but am not sure. How can I do this?
EDIT:
To clarify, I want to show the warning before the user submits the form. So, as they are filling out the form...
Use
> <input type="text" pattern="^[\x20-\x7F]+$" id ....>
in html
Use JavaScript to validate that form field.
Example (using jQuery):
<form>
<input name="whatever" id="fieldId">
...
</form>
<script type="text/javascript">
/* Define a function to check the form field value */
function containsAllAscii(str) {
return /^[\000-\177]*$/.test(str); // returns true if all are ASCII characters. false otherwise.
}
/* Now a little jQuery */
$('#fieldId').on('change', function() {
str = $(this).val();
is_valid = containsAllAscii(str);
if (!is_valid) {
window.alert("There are Non-ASCII characters in the input field");
}
});
</script>
The above code will check the given field's value whenever it changes (i.e. loses focus). You can use .on('keyup', ... instead of .on('change', ... which will check the field's value as the user is typing.
Finally, the error message that is shown is just a browser alert. Which is crappy. You can display a beautiful error message, you just need to learn a little more of jQuery. But I hope I've given you a good starting point.
Credits:
The code for containsAllAscii function is taken from this answer by Juan Mendes.
In your django form, create a custom field and take advantage of the media class.
from django import forms
class MyWidget(forms.TextInput):
class Media:
css = {
'all': ('pretty.css',)
}
js = ('animations.js', 'actions.js')
and set the js to the javascript file you will use for validation. something along the lines of the the other answer
https://docs.djangoproject.com/en/1.9/topics/forms/media/

jQuery validation plugin - how to style 1 validation message differently to others

I have a form that is being validated with the jQuery validation plugin successfully.
Messages are displayed in the correct position and in the correct situations.
So far, so good.
I have 1 field that is being validated correctly, but I need to position that 1 validation message differently to the others. With 2 inputs next to each other, I want the validation to appear under them both (ie under the block that wraps them both) rather than to the right per individual inputs.
The validation on these 2 inputs are dependent on each other, ie at least one must have input. The validation rule works, it's just the positioning I'm struggling with.
I'm using the following validation syntax:
$('#formId').validate({
rules: {
},
messages : {
}
}
In my HTML I have created a label specifically for the (radio) field I am trying to customise:
<label for="radioName" id="radioNameId-invalid" class="error"">Some error message</label>
I tried adding content to the 'showErrors' function of validate, which works, but seemingly then doesn't show any of the other validation messages in my page.
showErrors: function(errors) {
var collectionMethodError = errors['collectionMethod'];
if(collectionMethodError) {
$('#radioNameId-invalid').text(errorString);
$('#radioNameId-invalid').css("display","block");
}
}
I want to enable this error AND then allow validator to continue to do its default behaviour for other fields.
If I remove the showErrors function, the other validation messages are displayed but not my custom one.
How can I get both behaviours?
I ended up using the errorPlacement function instead of the showErrors function:
errorPlacement: function(error, element){
$(error).insertAfter(element);
// special case for display
if($(element).attr("name")=="radioName") {
$(error).insertAfter("#anElement"));
$("label[for=radioName].error").attr("id","invalid-radio-message");
}
}
So in short I'm adding an ID to a label that validation plugin adds, then styling to that ID in my css.
That seems to do what I was trying to do. Now to workout the re-hiding of the message!

Mvc Telerik grid cancel cell changes when input invalid

I am facing a small problem regarding input validation in mvc telerik grid.
I have it set to batch editting and I'm modifing the cells in an InCell mode.
Now whenever a user enters an invalid value in one of the inputs(Telerik's comboboxes/autocompletes), I'd like to display a message that
the entered value is iligal(this far I've managed on my own).
In addition to the message I'd like to revert the cell's value to it's previus value before
the user input.
So far I've tried:
grid.CancelCell(this);
$('#grid .t-grid-edit-cell input[type="text"]').value or innerText = prevVal;
The closest so far was e.newVal = e.oldVal, although it sometimes throws me a wierd exception in the jquery scripts or displays the combobox's drop down.
All the validatios and things I've tried are from the grid's client event OnSave()
It's same like what i searched before and I have solution for you.
On your OnSave() method has event like OnSave(e) and that 'e' carry all the elemnts and functions inside in my example after validation if not ok i can change that value to old value. Also you can use inspecter element log to look up what is inside 'e'
function onSave(e){
if(!validation)
{
///
}
else
{
e.cell.firstChild.value = "0"; // that is my edited cell
}
}

Categories

Resources