In Dart 3, one of the powerful features you can leverage is extensions. Extensions allow you to add new functionality to existing libraries. In this article, we will demonstrate how to extend theString
class to include common validation checks such as email validation, numeric check, and phone number validation.
Creating the String Extension
Let's start by creating an extension on theString
class. We will define three validation methods:
isValidEmail
- Checks if the string is a valid email format.isNumeric
- Checks if the string consists only of numeric characters.isPhoneNumber
- Checks if the string is a valid phone number.
Here's the code for theStringValidation
extension:
extensionStringValidationonString{boolgetisValidEmail{finalregex=RegExp(r'^[^@]+@[^@]+\.[^@]+');returnregex.hasMatch(this);}boolgetisNumeric{finalregex=RegExp(r'^-?[0-9]+$');returnregex.hasMatch(this);}boolgetisPhoneNumber{finalregex=RegExp(r'^\+?[0-9]{10,13}$');returnregex.hasMatch(this);}}
Explanation
- isValidEmail: This method uses a regular expression to check if the string follows a basic email pattern (e.g.,
example@test.com
). - isNumeric: This method checks if the string contains only numeric characters, including an optional leading minus sign for negative numbers.
- isPhoneNumber: This method validates if the string is a phone number. It allows an optional leading plus sign and checks for a length between 10 to 13 digits.
Usage
Using these extensions is straightforward. You simply call the new methods on any string instance. Below is an example demonstrating how to use these validation methods:
voidmain(){varemail="example@test.com";varphone="+1234567890";varnumber="12345";print(email.isValidEmail);// Output: trueprint(phone.isPhoneNumber);// Output: trueprint(number.isNumeric);// Output: true}
Explanation
- email.isValidEmail: Checks if the
email
string is a valid email. The output will betrue
if the string matches the email pattern. - phone.isPhoneNumber: Validates if the
phone
string is a valid phone number. The output will betrue
if the string matches the phone number pattern. - number.isNumeric: Checks if the
number
string consists of numeric characters. The output will betrue
if the string matches the numeric pattern.
Conclusion
By using Dart's extension methods, you can add reusable validation logic to theString
class. This approach makes your code cleaner and more modular. You can extend this pattern to include more validations as needed, enhancing the robustness of your applications.
Try integrating these extensions into your Dart projects and see how they can simplify your validation logic. Happy coding!
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse