Validating Phone Numbers to US Format in Dynamics 365 Power Apps
To validate phone numbers to a US format in Dynamics 365 Power Apps Model-Driven Apps, you can use JavaScript. I am going to show you how to enforce formatting and validation when users input a phone number.
1. Determine US Phone Number Format
The typical US phone number format is (XXX) XXX-XXXX or +1 (XXX) XXX-XXXX. You can validate this using regular expressions.
2. Add JavaScript Web Resource
- Navigate to Solutions in your Dynamics 365 instance.
- Create a new JavaScript web resource or update an existing one.
- Add the following script:
function validatePhoneNumber(executionContext) {
// Get the form context
var formContext = executionContext.getFormContext();
// Get the phone number field value
var phoneNumber = formContext.getAttribute("telephone1").getValue();
if (phoneNumber) {
// Define the US phone number regex pattern
var regexPattern = /^\(?([0-9]{3})\)?[-.\s]?([0-9]{3})[-.\s]?([0-9]{4})$/;
if (!regexPattern.test(phoneNumber)) {
// Show an error message if the number is invalid
formContext.getControl("telephone1").setNotification(
"Please enter a valid US phone number in the format (XXX) XXX-XXXX or XXX-XXX-XXXX."
);
} else {
// Clear the notification if the number is valid
formContext.getControl("telephone1").clearNotification();
}
}
}
3. Associate the Script with a Form Event
- Open the entity form where the phone number validation should occur.
- Navigate to Form Properties.
- Add the JavaScript web resource you created.
- Add an OnChange event to the phone number field (e.g.,
telephone1) and bind it to thevalidatePhoneNumberfunction.
4. Test the Validation
Open the form in your Dynamics 365 app. Enter different phone numbers to verify the validation logic.
5. Optional Formatting
If you'd like to automatically format the number to (XXX) XXX-XXXX after validation, extend the script:
function formatPhoneNumber(executionContext) {
var formContext = executionContext.getFormContext();
var phoneNumber = formContext.getAttribute("telephone1").getValue();
if (phoneNumber) {
var regexPattern = /^\(?([0-9]{3})\)?[-.\s]?([0-9]{3})[-.\s]?([0-9]{4})$/;
if (regexPattern.test(phoneNumber)) {
var formattedPhone = phoneNumber.replace(regexPattern, "($1) $2-$3");
formContext.getAttribute("telephone1").setValue(formattedPhone);
formContext.getControl("telephone1").clearNotification();
}
}
}
Add this function to the OnChange event of the field in addition to validation.
Key Considerations
- Replace
telephone1with the actual logical name of your phone number field if it differs. - Test thoroughly to ensure compatibility with your app and workflows.
- Consider user experience; avoid overly restrictive validation if not necessary.
No comments:
Post a Comment