Created
June 9, 2023 09:18
-
-
Save amitasehrawat/d6ac6c7218f1a78830f53709de63b686 to your computer and use it in GitHub Desktop.
Cypress- Common Regular Expression Examples
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// test.spec.js | |
describe('Regular Expressions in Cypress', () => { | |
it('should demonstrate the usage of regular expressions', () => { | |
// Example 1: Validating an email address using regex | |
cy.get('#email-input').type('example@test.com'); | |
cy.get('#email-input').should('match', /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/); | |
// Example 2: Verifying the presence of a phone number using regex for format "Phone: +XXX-XXX-XXX-XXXX", where X represents a digit | |
cy.contains(/^Phone:\s+\+\d{1,3}-\d{3}-\d{3}-\d{4}$/); | |
/* | |
Example 3: Verifying following date formats: | |
Date Format YYYY-MM-dd using separator '-' | |
Date Format dd-MM-YYYY using separators - or . or / | |
Date Format dd-mmm-YYYY using separators - or . or / | |
*/ | |
//Date Format YYYY-MM-dd using separator '-' | |
const dateRegex1 = /^\d{4}-\d{2}-\d{2}$/; | |
cy.get('#date-field').should('match', dateRegex1); | |
//Date Format dd-MM-YYYY using separators '-' or '.' or '/': | |
const dateRegex2 = /^\d{2}[-./]\d{2}[-./]\d{4}$/; | |
cy.get('#date-field').should('match', dateRegex2); | |
//Date Format dd-mmm-YYYY using separators '-' or '.' or '/': | |
const dateRegex3 = /^\d{2}[-./](?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[-./]\d{4}$/i; | |
cy.get('#date-field').should('match', dateRegex3); | |
// Example 4: Matching URL pattern | |
const urlRegex = /^(https?):\/\/(www\.)?([\w-]+)\.([\w.-]+)\/?([\w-]+)?$/; | |
cy.url().should('match', urlRegex); | |
/* | |
Example 5: Validating a password strength using regex | |
The regular expression enforces the following password requirements: | |
The password must contain at least one uppercase letter ([A-Z]). | |
The password must contain at least one lowercase letter ([a-z]). | |
The password must contain at least one digit (\d). | |
The password must contain at least one special character from the set [@#$%^&+=]. | |
The password must be at least 8 characters long. | |
*/ | |
cy.get('#password-input').type('Strong@Password123'); | |
cy.get('#password-input').should('match', /^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[@#$%^&+=]).{8,}$/); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment