cancel
Showing results for 
Search instead for 
Did you mean: 
Reply
inanoffice23
Resolver I
Resolver I

What is the best place to put custom validation code?

I found a couple of validation codes, and I made a mix and match, (this is the 'shortest' way to validate fields I have found online, I would love to see a shorter version even!) 

 

I currently put all of the below on each form, I find that if I put it too low, the set required won't be seen by Javascript and I then place it a bit too high, but it then hides the functions underneath, I tried removing semicolons, brackets, but I can't seem to win, at some point Javascript stops running and it doesn't read the whole .js code

 

I believe I might be able to add it as a content snippet, but it would be painful to have to place it for every page, or is there a way to leave it alone in one place, and pull it for every single page? The code I want to isolate is below

 

Then on each .js form I'd add whichever fields I required

 

if(varName !== null){
setRequired('Name', message);
setOptional('Surname', message);
}

 

 

setRequired = function (fieldName) {
  var $label = $("#" + fieldName + "_label");
  $label.parent().addClass("required");
  addValidator(fieldName, $label.text());
};

setOptional = function (fieldName) {
  var $label = $("#" + fieldName + "_label");
  $label.parent().removeClass("required");
  removeValidator("RequiredFieldValidator" + fieldName);
};

addValidator = function (fieldName, label) {
  var nV = document.createElement("span");
  var message = "<span class='font-weight-bold'>" + (typeof label === "string" ? label : fieldName) + "</span> is a required field.";
  nV.style.display = "none";
  nV.validationGroup = "";
  nV.initialvalue = "";
  nV.id = "RequiredFieldValidator" + fieldName;
  nV.controltovalidate = "#" + fieldName;
  nV.errormessage = "<a href=\'#" + fieldName +
      "_label\' onclick=\'javascript&colon;scrollToAndFocus(\"" + fieldName + "_label\",\"" +
      fieldName + "\");return false;\'>" + message + "</a>";
  var $field = $("#" + fieldName);
  nV.evaluationfunction = function () {
      var value = $field.val();
      return typeof value === "string" && value !== "";
  };
  var $validator = $field.closest("td").find("div.validators");
  if ($validator.length === 0) {
      var $info = $field.closest("td").find("div.info");
      $validator = $("<div class='validators'></div>").appendTo($info);
  }
  $validator.append(nV);
  Page_Validators.push(nV);
};

removeValidator = function (validatorId) {
  $.each(Page_Validators, function (index, validator) {
      if (validator !== null && validator !== undefined &&
          validator.id === validatorId) {
          Page_Validators.splice(index, 1);
      }
  });
};

 

 

1 ACCEPTED SOLUTION

Accepted Solutions
inanoffice23
Resolver I
Resolver I

Thank you so much for your help @OliverRodrigues I just had to do 2 things to solve this, one upload the file as Javascript file, and 2 remove the document ready line 🙂 I removed the ~ too just in case

 

When uploading your Javascript as a Web File, some people from the Power Pages community tend to omit the .js extension name, this way they can overcome the 'file not allowed' error
The issue with this, is that the mimetype will be application/octet-stream and you will encounter this error when you set your Security settings
Refused to execute script from 'https://yourportal.powerappsportals.com/Validation.js' because its MIME type ('application/octet-stream') is not executable, and strict MIME type checking is enabled.
You can only find the mimetype in your Javascript webfile.yml file, from Visual Studio Code, as it doesn't seem to be visible from Power Pages Management or Advanced settings, as far as I have seen

Solution:
Power Apps
Settings > Advanced settings
Administration > System Settings
Set blocked file extensions for attachments: delete js;
This way it will allow you to upload a .js file as a Web File
Once uploaded, add the .js; as a blocked file extension again
You will see from Visual Studio Code that your webfile.yml says mimetype: application/javascript and it won't give you any further errors

View solution in original post

9 REPLIES 9
OliverRodrigues
Most Valuable Professional
Most Valuable Professional

Instead of putting that on each form/page, you can do the following:

  • Create a single .JS file with all your "common/reusable code"
  • Upload this as a Web Rile
    • in the file itself, remove the .js extension
    • in the Partial URL you can keep .js as extension
  • Update/Create the Content Snippet called Tracking Code
    • this snippet runs on every portal page load
    • add the reference to your JS library there

There you go.. you can now reuse your code no matter where you are, let me know if you need help with any of the steps above 




If you like this post, give a Thumbs up. Where it solved your request, Mark it as a Solution to enable other users find it.

Power Pages Super User | MVP


Oliver Rodrigues


 

inanoffice23
Resolver I
Resolver I

Thank you @OliverRodrigues 

 

I added this to the Content Snippet which I called Tracking Code, set value below as HTML

 

<script type="text/javascript" src="~/Validation.js"></script>

 

I uploaded web file without the .js extension and partial url is Validation.js 

 

I tried to add in a multi step form Javascript (form options) the below, and it gives an Uncaught ReferenceError: setRequired is not defined

 

When I looked in Youtube, they added a note to the webfile to upload the file, however I can't seem to have that option, only 'File content', I wonder if that is why? 

 

Otherwise, I wonder what I am missing?

 

 

 

setRequired('bsbt_name', message);

 

 

 

 

 

 

 

 

 

 

$(document).ready(function () { 

setRequired = function (fieldName) {
var $label = $("#" + fieldName + "_label");
$label.parent().addClass("required");
addValidator(fieldName, $label.text());
};

setOptional = function (fieldName) {
var $label = $("#" + fieldName + "_label");
$label.parent().removeClass("required");
removeValidator("RequiredFieldValidator" + fieldName);
};

addValidator = function (fieldName, label) {
var nV = document.createElement("span");
var message = "<span class='font-weight-bold'>" + (typeof label === "string" ? label : fieldName) + "</span> is a required field.";
nV.style.display = "none";
nV.validationGroup = "";
nV.initialvalue = "";
nV.id = "RequiredFieldValidator" + fieldName;
nV.controltovalidate = "#" + fieldName;
nV.errormessage = "<a href=\'#" + fieldName +
"_label\' onclick=\'javascript&colon;scrollToAndFocus(\"" + fieldName + "_label\",\"" +
fieldName + "\");return false;\'>" + message + "</a>";
var $field = $("#" + fieldName);
nV.evaluationfunction = function () {
var value = $field.val();
return typeof value === "string" && value !== "";
};
var $validator = $field.closest("td").find("div.validators");
if ($validator.length === 0) {
var $info = $field.closest("td").find("div.info");
$validator = $("<div class='validators'></div>").appendTo($info);
}
$validator.append(nV);
Page_Validators.push(nV);
};

removeValidator = function (validatorId) {
$.each(Page_Validators, function (index, validator) {
if (validator !== null && validator !== undefined &&
validator.id === validatorId) {
Page_Validators.splice(index, 1);
}
});
};
})

 

 

 

 

 

 

 

OliverRodrigues
Most Valuable Professional
Most Valuable Professional

"When I looked in Youtube, they added a note to the webfile to upload the file, however I can't seem to have that option, only 'File content', I wonder if that is why? "

 

File Content is absolutely fine, the videos are probably older and using the classic data model, you are probably using the Enhanced Data Model.

A few snapshots of my enviornment:

Tracking Code:

 

OliverRodrigues_0-1710156866366.png

Web File:

OliverRodrigues_1-1710156995835.png

 

Also, did you clear the server-side cache? 

 




If you like this post, give a Thumbs up. Where it solved your request, Mark it as a Solution to enable other users find it.

Power Pages Super User | MVP


Oliver Rodrigues


 

Thank you for the screen shots, I have the same settings

 

I believe it is where I am placing the Javascript, although not too sure where to place it exactly

 

I had it under the display change, and I moved it to the top, but it's still complaining about some HTML error

 

Uncaught ReferenceError: setRequired is not defined
at HTMLDocument.<anonymous>

 

$(document).ready(function () {
  setRequired('bsbt_name', message);
  $("#gpbt_customertype").change(onDisplaySectionChange);
  onDisplaySectionChange();
});

var customertype;

function onDisplaySectionChange() {
var  customertype = $("#bsbt_customertype").find("option:selected").text();
}

 

 

 

OliverRodrigues
Most Valuable Professional
Most Valuable Professional

a few things to try:

  • <script type="text/javascript" src="~/Validation.js"></script>

    • you dont need the ~ symbol.. although I wouldn't say that's the issue
  • can you try to access your JS file to make sure it's accessible
    • for example: <portal>.powerappsportals.com/validation.js
  • can you try to call your method via Browser Console?
  • can you check via Browser Dev Tools if your file is being loaded?



If you like this post, give a Thumbs up. Where it solved your request, Mark it as a Solution to enable other users find it.

Power Pages Super User | MVP


Oliver Rodrigues


 

Thank you, btw I forgot to reply that yes I cleared the cache and yes I have the enhanced data model type

 

When I look for the file in the url it does load up and allows me to download the file

 

It loads in the Resources section of Dev Tools

 

If I try to call the method, it reads the setOptional or setRequired but when it comes to typing message, it doesn't seem to find it, it gives me an undefined error

 

I checked Stackoverflow and they suggest I haven't declared the variable 'You are sending data as the body of your request, but first you have to defined the object you are sending to API' and I tried to place the variables before the document ready in the multistep form Javascript, Console.pngas mentioned in the link, but no luck so far

javascript - Uncaught ReferenceError: data is not defined at HTMLDocument.<anonymous - Stack Overflo...

 

It seems to give a slightly different message now Uncaught TypeError: setRequired is not a function

 

Wondering if this has anything to do with it - The preprocessors or packer will wrap your code in a seperate scope to prevent filling up the global space. How to fix the error "uncaught reference error: data is not defined" using javascript? - Stack Overf...
 

OliverRodrigues
Most Valuable Professional
Most Valuable Professional

Hi, I think one issue here is that you haven't defined "message" before calling the method:

  setRequired('bsbt_name', message);

 

can you change this to:

  var message = "hello world";
  setRequired('bsbt_name', message);



If you like this post, give a Thumbs up. Where it solved your request, Mark it as a Solution to enable other users find it.

Power Pages Super User | MVP


Oliver Rodrigues


 

I guess you mean in the multistep form, it keeps giving me the error. In theory the message variable has been defined after the 'addvalidator' 

Uncaught ReferenceError: setRequired is not defined
    at HTMLDocument.<anonymous>

 

inanoffice23
Resolver I
Resolver I

Thank you so much for your help @OliverRodrigues I just had to do 2 things to solve this, one upload the file as Javascript file, and 2 remove the document ready line 🙂 I removed the ~ too just in case

 

When uploading your Javascript as a Web File, some people from the Power Pages community tend to omit the .js extension name, this way they can overcome the 'file not allowed' error
The issue with this, is that the mimetype will be application/octet-stream and you will encounter this error when you set your Security settings
Refused to execute script from 'https://yourportal.powerappsportals.com/Validation.js' because its MIME type ('application/octet-stream') is not executable, and strict MIME type checking is enabled.
You can only find the mimetype in your Javascript webfile.yml file, from Visual Studio Code, as it doesn't seem to be visible from Power Pages Management or Advanced settings, as far as I have seen

Solution:
Power Apps
Settings > Advanced settings
Administration > System Settings
Set blocked file extensions for attachments: delete js;
This way it will allow you to upload a .js file as a Web File
Once uploaded, add the .js; as a blocked file extension again
You will see from Visual Studio Code that your webfile.yml says mimetype: application/javascript and it won't give you any further errors

Helpful resources

Announcements

Check out the Copilot Studio Cookbook today!

We are excited to announce our new Copilot Cookbook Gallery in the Copilot Studio Community. We can't wait for you to share your expertise and your experience!    Join us for an amazing opportunity where you'll be one of the first to contribute to the Copilot Cookbook—your ultimate guide to mastering Microsoft Copilot. Whether you're seeking inspiration or grappling with a challenge while crafting apps, you probably already know that Copilot Cookbook is your reliable assistant, offering a wealth of tips and tricks at your fingertips--and we want you to add your expertise. What can you "cook" up?   Click this link to get started: https://aka.ms/CS_Copilot_Cookbook_Gallery   Don't miss out on this exclusive opportunity to be one of the first in the Community to share your app creation journey with Copilot. We'll be announcing a Cookbook Challenge very soon and want to make sure you one of the first "cooks" in the kitchen.   Don't miss your moment--start submitting in the Copilot Cookbook Gallery today!     Thank you,  Engagement Team

Announcing Power Apps Copilot Cookbook Gallery

We are excited to share that the all-new Copilot Cookbook Gallery for Power Apps is now available in the Power Apps Community, full of tips and tricks on how to best use Microsoft Copilot as you develop and create in Power Apps. The new Copilot Cookbook is your go-to resource when you need inspiration--or when you're stuck--and aren't sure how to best partner with Copilot while creating apps.   Whether you're looking for the best prompts or just want to know about responsible AI use, visit Copilot Cookbook for regular updates you can rely on--while also serving up some of your greatest tips and tricks for the Community. Check Out the new Copilot Cookbook for Power Apps today: Copilot Cookbook - Power Platform Community.  We can't wait to see what you "cook" up!      

Tuesday Tip | How to Report Spam in Our Community

It's time for another TUESDAY TIPS, your weekly connection with the most insightful tips and tricks that empower both newcomers and veterans in the Power Platform Community! Every Tuesday, we bring you a curated selection of the finest advice, distilled from the resources and tools in the Community. Whether you’re a seasoned member or just getting started, Tuesday Tips are the perfect compass guiding you across the dynamic landscape of the Power Platform Community.   As our community family expands each week, we revisit our essential tools, tips, and tricks to ensure you’re well-versed in the community’s pulse. Keep an eye on the News & Announcements for your weekly Tuesday Tips—you never know what you may learn!   Today's Tip: How to Report Spam in Our Community We strive to maintain a professional and helpful community, and part of that effort involves keeping our platform free of spam. If you encounter a post that you believe is spam, please follow these steps to report it: Locate the Post: Find the post in question within the community.Kebab Menu: Click on the "Kebab" menu | 3 Dots, on the top right of the post.Report Inappropriate Content: Select "Report Inappropriate Content" from the menu.Submit Report: Fill out any necessary details on the form and submit your report.   Our community team will review the report and take appropriate action to ensure our community remains a valuable resource for everyone.   Thank you for helping us keep the community clean and useful!

Hear what's next for the Power Up Program

Hear from Principal Program Manager, Dimpi Gandhi, to discover the latest enhancements to the Microsoft #PowerUpProgram, including a new accelerated video-based curriculum crafted with the expertise of Microsoft MVPs, Rory Neary and Charlie Phipps-Bennett. If you’d like to hear what’s coming next, click the link below to sign up today! https://aka.ms/PowerUp    

Welcome! Congratulations on joining the Power Pages community!

Welcome to the Power Pages Community!   You're now a part of a vibrant group of peers and industry experts who are here to network, share knowledge, and even have a little fun.     Now that you're a member, you can enjoy the following resources:   The Power Pages Community Forums The forums are also a great place to connect with other Power Pages community members. Check the News & Announcements section for community highlights, find out about the latest community news, and learn about the Community Team. Share your feedback, earn custom profile badges, enter challenges to win prizes, and more.   Community Blog Our community members have learned some excellent tips and have keen insights on the future of business analysis. Head on over to the Community Blog to read the latest posts from around the world. Let us know if you'd like to become an author and contribute your own writing — everyone is welcome.   And that’s not all, we have Galleries of additional information such as the Community Connections & How To Videos & Webinars & Video Gallery and more to motivate, educate and inspire you.   Again, welcome to the Power Pages community family, we are so happy you have joined us! Whether you are brand new to the world of data or you are a seasoned veteran - our goal is to shape the community to be your ‘go to’ for support, networking, education, inspiration and encouragement as we enjoy this adventure together! Let us know in the Community Feedback forum if you have any questions or comments about your community experience, but for now – head on over to the forums Get Help with Power Pages and dive right in!   To learn more about the community and your account be sure to visit our Community Support Area. We look forward to seeing you in the Power Pages Community!   The Power Pages Community Team  

Users online (4,535)