Aurelia Validation - Stop property name appearing in error message - javascript

I'm using the new aurelia-validation packages and when a validation fails the error message that is created contains the property name. Quite often the underlying property name isn't very user friendly so you don't want to show it on the page.
ValidationRules
.ensure('isDeliveryAddressValid').required()
.on(this.order);
I have tried added a custom message to validation rules but this just appends something different on to my property name.
ValidationRules
.ensure('isDeliveryAddressValid').required({message:'must have a value.'})
.on(this.order);
Is there a way to remove the property name from the validation error so my validation renderer can show a better message?

This is a quirk of validate.js, the underlying validation engine for aurelia-validatejs. Searching through their docs I found:
If you need an error not to be prefixed by the attribute add a leading ^ to the error and it won't be prepended.
So something like this should work:
ValidationRules
.ensure('isDeliveryAddressValid').required({message:'^Delivery Address Valid must have a value.'})
.on(this.order);

Related

Validation without objects using Joi

good evening.
I'm having trouble while trying to validate a variable using Joi. I've read this page link
Joi usually validates object through schemas, however, the page I mentioned show that Joi also supports a more "direct" approach to validation. In my case, I'm trying just to validate a variable.
I'm trying the following:
const {error, value} = Joi.number().validate("SAMPLE TEXT");
It's not precisely what I'm trying to do (I'd change "SAMPLE TEXT" for a variable), but It's a good example to show my problem.
What I'd expect from this code is that an error is thrown (because validation should fail), meaning that ** error should not be null or undefined **, however, when trying:
console.log(`Error: ${error}`};
I get:
Error: undefined
Can anyone help me?
[]
Check your package is installed perfectly. I did not find any issue in your code. I have run it properly.
const Joi = require('#hapi/joi'); check this line also

Python 3 Selenium fails to execute javascript

I'm using python 3 and I'm using Selenium to try to scrape data off a website. I need to remove a class from a list item in order to display the data I need, this is the code:
driver.execute_script("document.getElementsByClassName('otherClassName isSelected').classList.remove('isSelected');")
but I get the error
"selenium.common.exceptions.WebDriverException: Message: unknown error:
Cannot read property 'remove' of undefined"
I have also tried
driver.execute_script("document.getElementsByClassName('otherClassName isSelected').setAttribute('class', 'otherClassName')")
but then I get
selenium.common.exceptions.WebDriverException: Message: unknown error: document.getElementsByClassName(...).setAttribute is not a function
I guess this is because you're trying to apply class name update for multiple elements at once while setAttribute() allows to apply changes to one element at the time.
Try below code instead
js = """document.querySelectorAll('.otherClassName.isSelected')
.forEach( x=> x.setAttribute("class","otherClassName"));"""
driver.execute_script(js)
P.S. It seem to be XY problem as usually you don't need to make changes to page source while page scraping. You should share more details about your initial problem
I had forgotten to add [0] after getting the element by class, so the correct code should be:
driver.execute_script("document.getElementsByClassName('otherClassName isSelected')[0].classList.remove('isSelected');")

Multiple errors per field in Mongoose validation

Has anyone workaround for getting all errors per field in Mongoose validation? Right now, when some field has an error, validation for that field stops, because of that, you need to resubmit form to see next error.
This behaviour might be fixed in future (https://github.com/Automattic/mongoose/issues/2612), but before that, I would love to see a workaround, which would let me to use validation method, for e.g.:
User.schema.path('hashed_password').validate(function (value) {
if ( ! something)
this.invalidate('password', 'Something is wrong with the password');
});
Note: Using validation method, I can bind error to any field, not just the one validated at the moment. Right now there is no plugin which would let me do that (I have tested mongoose-validator-all and mongoose-validate-all and those plugins are using different strategy).

custom error display with parsley.js 2.x

I need to show a list of validation errors in a popup.
I've disabled UI modification with <form data-parsley-ui-enabled="false"... and subscribed to the "parsley:field:error" event, where I collect error information, and then on "parsley:form:validated" I display the popup, ofcourse only on the condition isValid() == false.
But I am having problems with getting the actual error message in the "parsley:field:error" handler. The handler gets a single parameter containing an object, which so far I inspected to have several properties:
$element - the actual jQuery field,
constraints - list of constraints
options.i18n - it has some raw error message strings which I can get iterating with an n variable like so: obj.options.i18n.<LANGUAGE_CODE>.[obj.constraints[n].name], but they ocasionally contain placeholders (%s) and therefore are not suitable for display to the end
user; and sometimes there's an array instead of a single string, which defeats the idea completely;
The question is, how do I get the actual error message which would got displayed if I hadn't disabled the UI?
Solution
Use the following way to access a prioritized error message (i.e data-parsley-priority-enabled=true):
$.listen('parsley:field:error', function(parsleyField) {
// parsley field
console.log(parsleyField);
// which constraint has failed
console.log(parsleyField.validationResult[0].assert.name);
// the data-parsley-<constraint>-message
console.log(parsleyField.options[parsleyField.validationResult[0].assert.name+'Message']);
// the default constraint fail message
console.log(window.ParsleyValidator.getErrorMessage(parsleyField.validationResult[0].assert));
});
Short Explanation
You were almost there, the messages are stored in the options object itself, and the format for the message is like this: <constraint>Message, for example: requiredMessage.
Which is similar to the "data attribute to js variable conversion" convention like in jQuery, this has been mentioned in the docs: <parsleynamespace>-<constraint>-message becomes <constraint>Message.
Got this idea after seeing the annotated source for ui.js, check the _getErrorMessage function.
To access all the validation messages for a field on error (i.e data-parsley-priority-enabled=false), you can simply iterate through the
parsleyField.validationResult array:
for (i=0; i<parsleyField.validationResult.length; i++) {
console.log(parsleyField.options[parsleyField.validationResult[i].assert.name+'Message']);
}

(Protractor) Checking whether an input is disabled on click?

I have two input fields, Username and Password and a spinner button. When i click on this spinner button these two input fields get disabled and I am redirected to another page. I am writing an end-to-end testing to check whether these input fields are disabled.
element(by.model('username')).sendKeys('rabi');
element(by.model('password')).sendKeys('rabi');
/* click on spin button */
spinBtn = element(by.className('call-to-action'));
spinBtn.click();
/* check if input is disabled */
var loginInput = element(by.id('login-username'));
expect(loginInput.isEnabled()).toBe(false);
The previous example of
expect(loginInput.getAttribute('disabled')).toEqual('disabled');
Will not work for checking if something is enabled.
You should use
expect(loginInput.isEnabled()).toBe([true|false]);
to accurately verify if something is enabled/disabled.
If that isn't working for you, there's probably something else going on.
I want to add that #TaylorRose's answer (the most voted answer) is very good and thank him for that.
// passes when the button does not have 'disabled' attribute
expect($('#saveChangesBtn').isEnabled()).toBe(true);
However when I tried to run this I got an error:
Error: TSError: тип Unable to compile TypeScript e2e/specs/element.e2e-spec.ts:
Argument of type 'false' is not assignable to parameter of type 'Expected<Promise<boolean>>'.
There are multiple solutions to this issue and here are two of them:
1.Cast your expect to type 'any'
expect<any>($('#saveChangesBtn').isEnabled()).toBe(true);
2.Add #types/jasminewd2 to your package json (and run 'npm install' of course) (thanks to aktraore#github)
"devDependencies": {
...,
"#types/jasminewd2": "2.0.6",
...
}
And then no more errors from typescript and it solves this problem.
P.s. Version 2.0.6 is the latest as of writing this post and the magic version could be different for your case.
So this is addition to the most voted answer if anybody here is having this issue.
When using "getAttribute('disabled').toEqual('true') " did not work
I used className instead, to complete my test, as the classNames changed when disabled.

Categories