This blog post will discuss what is HTML5 form validation is, and give a sneak peek as to how Cypress can be used to automate the same.
Before we dive into how to handle html form validation using cypress, let us understand what is HTML form validation.
HTML5 supports client side form validation, which means the information entered by the user gets validated in the client side without being sent to server.
Below is the sample html inbuilt form validation
<form action="/action_page.php" method="post">
<div>
<label for="fname">FirstName</label>
<input id="fname" type="text" name="fname" required placeholder="First Name"/>
</div>
<div>
<label for="lname">LastName</label>
<input id="lname" type="text" name="lname" required placeholder="Last Name"/>
</div>
<div>
<label for="email">Email</label>
<input id="email" type="email" name="email" required placeholder="Email"/>
</div>
<div>
<input type="submit" value="Submit">
</div>
Now let us see how we can handle the above scenario using Cypress.
The inbuilt html validation errors are shown by the browsers and are not part of the DOM. There for we cannot check them from Cypress. We can make use of CSS pseudo-class defined by html standards for finding invalid and valid input fields
Check Number of fields which are invalid
When user submits the form without filling any of the input fields or by keeping them blank. Since all 3 fields are marked as required in the above example, the invalid field count should be 3. Let us check that using Cypress.
it('Verify html form validation', () => {
cy.get('input[type="submit"]').click();
cy.get('input:invalid').should('have.length', 3);
})
All 3 input fields has a pseudo-class :invalid
How to Check Validation Messages
In case of validation error each element will have a property called validationMessage. Let's make use of that to validate the error messages.
This time lets fill some data into the fields
it('Verify html form validation', () => {
//Enter valid format into the first name last name and invalid email format
cy.get('#fname').type(123)
cy.get('#lname').type('%^&^');
cy.get('#email').type('test@');
//Click on submit and check the number of invalid fields
cy.get('input[type="submit"]').click();
cy.get('input:invalid').should('have.length', 1);
//Validate the error messages using validationMessage property
cy.get('#email').invoke('prop', 'validationMessage')
.should('equal', "Please enter a part following '@'. 'test@' is incomplete.");
})
And that's it. As you can see, it is pretty simple to automate html form-validation with Cypress. Hopefully this guide helped you get on the right track with writing tests for your website. Make sure to follow Cypress @cypress_io and check out their list of courses at Cypress Learn for more tutorials and guides like this one!
Top comments (0)