How To Validate Postcodes In Model Driven App Forms [Solution Sunday #5]

How To Validate Postcodes In Model Driven App Forms [Solution Sunday #5]

Advanced validation has always been difficult to handle using Business Rules and out-of-the-box functionality in Power Apps.

In this iteration of Solution Sunday, I will show you in 4 easy steps, how you can apply JavaScript code into your forms, so that you never get an invalid postcode in your database again.

I aim to make these Solution Sundays accessible to all, whether you're a citizen developer or a professional programmer. If you're not familiar with JavaScript, don't worry, I will give you everything you need in this article.

What will this code achieve:

  • It will stop invalid characters such as "@" "/", etc from being saved in postcodes.
  • It will automatically make the postcode upper case, so the user can focus on their task at hand.
  • It will prevent incorrect postcode formats.
  • It will allow postcodes with spaces if spaced correctly, and valid postcodes without spaces (For example, PO1 2GP & PO12GP are both valid)

Requirements

  • An existing Postcode Field in your table that is single line text.
  • A Form with the Postcode Field included in it.


Step 1 - Save the code on your machine

You can copy the validation code below and save it onto your machine as a .js file.

To do this, open up Visual Studio Code and create a new file.

Save the file as [YOUR CHOSEN NAME].js, and you should be ready to go.

The only thing that needs to be changed in the code is 'hrashid_postcode'. Please replace this with your unique Postcode field name.

If you're unique Postcode field name is 'hrashid_postcode' then I'm flattered, and you can skip this step.

// UK Postcode Validation Function
function validateUKPostcode(postcode) {
    // Convert postcode to uppercase for validation
    var upperCasePostcode = postcode.toUpperCase();
    
    // Define the regex pattern for UK postcodes (with optional spaces)
    var postcodePattern = /^(?:(?:[A-PR-UWYZ][A-HK-Y]?[0-9][0-9ABEHMNPRV-Y]?)|(?:[A-PR-UWYZ][0-9][A-HJKSTUW]?|[A-PR-UWYZ][A-HK-Y][0-9][ABEHMNPRVWXY]?))\s?[0-9][ABD-HJLNP-UW-Z]{2}$/i;
    
    // Trim the input to remove any leading or trailing whitespace
    var trimmedPostcode = upperCasePostcode.trim();

    // Check if the postcode matches the regex pattern
    if (!postcodePattern.test(trimmedPostcode)) {
        // Return error message if the postcode is not valid
        if (trimmedPostcode.length < 5 || trimmedPostcode.length > 8) {
            return "Postcode length should be between 5 to 8 characters.";
        } else if (!/^[A-Z0-9\s]*$/i.test(trimmedPostcode)) {
            return "Postcode contains invalid characters.";
        } else {
            return "Invalid postcode format.";
        }
    }

    // If the postcode is valid
    return "";
}

// Function to be called onChange of hrashid_postcode field
function onPostcodeChange(executionContext) {
    var formContext = executionContext.getFormContext();
    var postcode = formContext.getAttribute("hrashid_postcode").getValue();

    var validationMessage = validateUKPostcode(postcode);

    if (validationMessage) {
        // Display the error message
        formContext.getControl("hrashid_postcode").setNotification(validationMessage, "postcodeValidation");
    } else {
        // Clear any previous error message
        formContext.getControl("hrashid_postcode").clearNotification("postcodeValidation");
        // Set the postcode to uppercase
        formContext.getAttribute("hrashid_postcode").setValue(postcode.toUpperCase());
    }
}        

Step 2 - Add the code to your Solution and Form

Next, you need to add the code to your solution, and then the form you want to apply this validation on. If you're unsure how to do this, I've got a tutorial on my website here that you can check out:

Please complete Steps 2 & 3 above and feel free to come back here to configure the JS Library to the Event.

Step 3 - Configure the JS Library to the Event of your field

Now you should have the code accessible in your form through a JS Library.

To apply the code to your Postcode Field, so that it validates when someone enters something, you can use the image below to accompany you which match to the points below:

  1. Select the Postcode Field in your form.
  2. Select 'Events' in your right navigation.
  3. Select the 'On Change' property.
  4. Select '+ Event Handler'.
  5. Select the Postcode Validation Library you added in Step 2.
  6. Write 'onPostcodeChange' in the 'Function' box.
  7. Ensure you tick the 'Pass Execution context as first parameter' box.

LinkedIn won't let me make this image bigger, so please zoom in to read as needed.

Step 4 - Publish your Form and have a test!

Postcode validation working.

Thank you for reading this article and I hope you find this useful.

If you have any suggestions for next iterations of Solution Sunday, please feel free to leave them in the comments :)

Until next time, take it easy.

Brian Archer

Principle Microsoft 365 Platform Engineer @ Ofgem | Power Platform | Microsoft 365 | Microsoft Azure | Azure Devops

8 个月

Can I just say how useful I have found your Solution Sunday content. I have been using it to get comfortable with JavaScript in Model-Driven apps to help me prepare for the PL-400 exam. Thanks!

要查看或添加评论,请登录

Howdang Rashid的更多文章

社区洞察

其他会员也浏览了