If testing my webapp using Selenium. All the form validation in the webapp is done using HTML5 form validations. Is there any way to assert if a form/input validation was tr
Testing for the presence of the HTML5 attributes that are responsible for the validation is adequate enough. Actually triggering the browser-implementation of the validation is not really testing your work (but instead testing the browser itself), which might be nice but in my opinion is unnecessary. How to do that is already covered in the top answer. My answer is just to expand with a defence-in-depth approach to form-field validation.
It is absolutely necessary that you have your own validation in addition to the HTML5 rules, for when HTML5 validation is not supported (or is bypassed).
The first problem is that the HTML5 validation takes precedence and prevents you from testing your own validation. So how to approach this?
To test it has been used, use assertAttribute:
assertAttribute
id=myFieldId@required
If for some reason you're using the XML syntax required="required", you will need to assert the value is "required".
If your HTML5 validation prevents your JavaScript validation from returning errors, after you have asserted that the HMTL5 validation attributes were present, you can remove the HTML5 validation attributes to test the fallback JavaScript validation:
runScript
document.getElementById('myFieldId').removeAttribute('required')
Now you can test your JavaScript validation. To remove email validation, you will need to set the field's type attribute to text:
runScript
document.getElementById('myFieldId').setAttribute('type','text')
Even when you use HTML5 validation and JavaScript validation, if you are submitting to a server, you will need to test your server validates these fields, too.
Calling a form's submit() function will submit the form without calling any validation. Selenium's submit command does the same thing:
submit
name=myFormName
After waiting for the next page to load, you can check the expected errors are present.