I am automating filling out an online form with CasperJS. Whenever you try to submit the form where you've filled out any of the required fields with invalid data, an error message appears by each of the fields that has invalid data to alert you to what the problem is. I would like to gather all of these messages and concatenate them into one - whether via an array or another method doesn't matter to me. The CSS for the error messages looks like this:
<span class="field-validation-error" data-valmsg-replace="true" data-valmsg-for="Name.Last">
<span class="" for="Name_Last" generated="true">
The Last Name field is required.
</span>
</span>
<span class="field-validation-error" data-valmsg-replace="true" data-valmsg-for="Address.City">
<span class="" for="Address_City" generated="true">
The City field is required.
</span>
</span>
In the browser console, I had success doing this:
var arr = document.querySelectorAll('.field-validation-error');
for (var i = 0; i < arr.length; i++) {
var err = arr[i]; console.log(err.textContent);
}
which returned me:
"The Last Name field is required."
"The City field is required."
I set out to do the same in CasperJS, but I can't get the same results. Here is my code so far (a snippet of a much larger file, so I won't post my casper.start or anything):
var results = self.evaluate(function() {
var arr = document.querySelectorAll('.field-validation-error');
return Array.prototype.map.call(arr, function(e) {
return e.getAttribute('textContent');
});
});
for (var i = 0; i < results.length; i++) {
console.log(results[i]);
}
This outputs three blank lines.
If I just return e and then console.log(results[i].textContent)), the script does print one error message correctly, but then crashes because the rest of the array is full of null objects! I thought Array.prototype.map was supposed to prevent this? How do I get the array of error messages out of this page via Casper?
You should be able to do this with the native CasperJS function getElementsInfo. It contains a text property for each element:
var texts = casper.getElementsInfo('.field-validation-error').map(function(info){
return info.text.trim();
});
e.getAttribute('textContent') obviously can't work, because there is no textContent attribute, but only a textContent property. The same code that you used in the browser console should have worked in PhantomJS. You may try to change .textContent to .innerText.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With