parsely js : adding custom validators - parsley.js

http://parsleyjs.org/
Trying to add custom validator for image field for image resolution.
window.Parsley.addValidator
is throwing error in console as windows.parsley is undefined or null.

window.ParsleyValidator.addValidator('myvalidator',
function (value, requirement) {`enter code here`
alert('myvalidator');
return false;`enter code here`
}, 32)
.addMessage('en', 'myvalidator', 'my validator failed');

Related

How can I make my custom JavaScript code work properly in AngularJS MVC?

As a simple example from my custom JavaScript file:
if(document.URL.indexOf("http://localhost/Angular/Angular_Project_01/index.html#!/myinfo") >= 0)
{
alert("you are viewing myinfo page");
}
This will only execute if page is refreshed while in the myinfo view. The problem is this page contains forms that need to be disabled after user has entered his/her information.
This code worked well for me in this project. Not sure if it's best practice though.
window.addEventListener('hashchange', function() {
if(window.location.hash == '#!/myinfo' //&& something)
{
console.log("Hash is #!/myinfo");
setTimeout(function() //Avoid TypeError: Cannot set property 'value' of null
{
//Do something
}, 1000);
}
});

Getting access to target element in parsley custom validators

I need to get access to the element that is being tested for custom rule in parsley custom validators. In other words, I need something like this:
window.Parsley.addValidator('uniqueInn', {
validateString: function(value)
{
$(THE ELEMENT BEING TESTED).closest('table')....;
// Some code
}
messages:
{
en: 'Custom message'
}
});
Is it possible in parsley ?
For version 2.7.2 you can do this:
Parsley.addValidator('uniqueInn', {
validateString: function(value, requeriment, instance)
{
var element = instance.element; // or instance.$element
}
messages:
{
en: 'Custom message'
}
});
The actual argument list for custom validators is: value, requirement, options, instance. That fourth argument is the parsley instance and you can use the $element attribute...
PR for better doc always welcome.

Is there a way for comparing dates on Valdr?

I'm using Valdr on my project and I need to validate that a date input "startDate" is before another date input "endDate".
<input id="startDate" name="startDate" type="text" ng-model="project.startDate"/>
<input id="endDate" name="endDate" type="text" ng-model="project.endDate"/>
I know that, without Valdr, this problem can be solved using a custom directive, as shown here: Directive for comparing two dates
I found a little unclear how to create a custom validator on Valdr that uses the values of other fields.
The answer is short but dissatisfactory: valdr does currently not support this. There is an open feature request on GitHub, though.
Until the feature gets implemented in valdr, you can use your own validator directive and kind of make it talk to valdr. The directive can require a 'form' and can get the names of the date models you want to compare. Then you do your logic to compare the two values and set the validity of the appropriate 'ngModelController'. Since you need to provide an error when setting the validity to that model, the error name will be your connection with valdr.
After that, you just only need to map the error in the 'valdrMessage' service:
.run(function (valdrMessage) {
valdrMessage.angularMessagesEnabled = true;
valdrMessage.addMessages({
'date': 'Invalid date!'
});
});
Valdr will show the message bellow the invalid field as usual.
Actually you can solve this through a custom validator, which can get another field and compare the values with each other. The code below is using the valdr-bean-validation for serverside generation of valodation.json.
If you want to use it without this, just look into the JS code and add the validator in your validation.json manually.
Java Annotation (serverside declaration of the valdr validator):
package validation;
#Documented
#Retention(RetentionPolicy.RUNTIME)
#Target({ ElementType.METHOD, ElementType.FIELD, ElementType.CONSTRUCTOR,
ElementType.PARAMETER, ElementType.ANNOTATION_TYPE })
public #interface DateFormat {
String message();
Class[] groups() default { };
String beforeFieldName();
}
Java Bean (usage of the annotation, this class has to be used in the generation of validation.json):
package pojo;
import validation.DateFormat;
public class RegistrationPojo implements BasePojo {
#NotNull(message = "message.date1.required")
private Date date1;
#NotNull(message = "message.date2.required")
#DateFormat(message = "message.date2.date", beforeFieldName = "date1")
private Date date2;
}
JS (implementation of the custom validator and registering it in valdr):
module.factory('validation.DateFormat', [
function () {
return {
name: 'validation.DateFormat',
validate: function (value, constraint) {
var minOk = true;
var maxOk = true;
var format = false; // constraint.pattern is mandatory
//do not validate for required here, if date is null, date will return true (valid)
console.log("my date validator called");
console.log(" beforeFieldName: " + constraint.beforeFieldName);
var field = document.querySelector('[name="' + constraint.beforeFieldName + '"]');
console.log("field value: " + (field ? field.value : "null"));
return (!field || value > field.value);
}
};
}]);
module.config([
"valdrProvider",
function(valdrProvider) {
valdrProvider.addValidator('validation.DateFormat');
}]);
You could go with this solution:
Have a bool value calculated upon changes in any of the date fields - a value indicating if the validation rule is met
Create a simple custom validator to check if that value is true or not
Register your validator and add a constraint for that calculated value
Place a hidden input for that calculated value anywhere you like your validation message to appear

Using Isotope plugin with requirejs

Ive added the Isotope plugin using these instructions: http://isotope.metafizzy.co/appendix.html#requirejs
Heres my code:
this.social = new Isotope('#latest-news', {
itemSelector: '.social-item',
layoutMode: 'fitRows',
sortBy: 'text',
getSortData: {
'text': '.text'
}
});
i then try to insert elements later on like so:
that.social( 'insert', elements );
but get the following error (On the insert function):
Uncaught TypeError: undefined is not a function
If i do a console.log(this.social) it does return an isotope object.
How can i call the 'insert' function, or any function for that matter? Otherwise where am I going wrong?
Went through the source code for a while, when using requirejs the insert method becomes:
that.social.insert( elements );
Basically use the vanilla JS versions of the methods.

Extjs - Multi validations VType email

I've a probllem with email textfield on which I want to perform multi validations. In detail:
1. Classic format email validation
2. Unique email check
Can I override email VType? or I have to create a custom VType? How can I perform two validation with two different error messages in a single VType?
Thanks
Regards
You can override the default validation using the validator attribute. For example, if you wish to enforce the standard rules and some other rules (e.g. defined by isSomeOtherRules() that returns a boolean), set the following attribute:
validator: function(value) {
return Ext.form.VTypes.email(value) && isSomeOtherRules(value);
}
Expanding on Andrew's post; we can return validation messages (shown below) to get the same look and feel of vtype error alert:
validator: function(value) {
if (!Ext.form.VTypes.cfpValidatePdf(value)) {
return 'File must be pdf';
} else if (!Ext.form.VTypes.cfpValidateFileNameSize(value)) {
return 'The maximum length of the filename is 64';
} else {
return true;
}
}

Resources