How to Validate forms built with Lightning Components

I recently had a requirement to create a basic lightning component to capture form inputs. I previously had a not so good experience with building custom validation with Lightning components back in Summer17 when lightning was pretty new. I was using force:inputField and also used lightning:inputField.

Past few years it has become more efficient and easier with just the lightning:input field and default HTML5 APIs.

I have a simple bank form that captures and validates the form as such and when submitted validates the required fields.

Form

For the Bank Account Name input field specify the required attribute as true and check the validity of the field.

I use reportValidity to display the error message in the input field

And for the Bank Account Number input field aside from setting the field as true, I also specified a regular expression pattern. And then used the setCustomValidity function to display a custom error message.

And that folks, is how easy to validate the input form. Hit the comments below if you need help building your validation.

How To Use Regular Expressions (Regex)

“Some people, when confronted with a problem, think ‘I know, I’ll use regular expressions.’ Now they have two problems.” – Jamie Zawinski

Every now and then I have some requirements where it entails parsing some data where I need to use some form of Regular Expression(regex), it is a syntax to use to search for patterns in a string or sets of strings. At first, the syntax looks intimidating and most people would shy away and resort to writing some functions to solve the issue.

Learning regex is a must-have skill to have as it can be applied to a wide range of tasks that needs some sort of search or parsing and is widely available in most programming languages, works on shells, text editors and IDEs, etc..). I use it most of the time when writing front end Javascript validation and backend logic in Apex NodeJS, Java/Groovy , Swift and Python

I created this cheat sheet that covers the basics and some handy tips.

Flags

The search pattern is normally delimited by two slash characters /abc/. At the end we can specify a combination of the following flags.

  • g (global) – Don’t return after the first match
  • m (multi-line) – ^ and $ match start/end of line
  • i (insensitive) case insensitive match
  • x (extended) ignore whitespace
  • X (eXtra) disallow meaningless escape
  • s (single line) dot matches new line
  • u (unicode) match with full unicode
  • U (Ungreedy) make quantifiers lazy
  • A (Anchored) anchor to start of pattern
  • J (Jchanged) allow duplicate subpattern names
  • D (Dollar end only) $ matches only end pattern


Anchors

Quantifiers

Or and Brackets

When inside bracket expressions all special character rules do not apply. E.g. \ to escape a character does not apply

Character Classes

In order to be taken literally, you must escape the characters ^.[$()|*+?{\with a backslash \ as they have special meaning.

Groupings

Greedy and Lazy Quantifiers

The quantifiers ( * + {}) are greedy operators, so they expand the match as far as they can through the provided text.

Boundaries

Back References – \1

Look-ahead and Look-behind

Top Regular Expressions

Summary

As we’ve learned regex is so powerful and its’s application is wide. Listed below some of few things you can do with regex within your project.

  • input and data validation –
    • validate user input in forms
    • validate data before applying logic or saving to database
    • validating JSON schema
  • replacing values – replace specific data in a string
  • text parsing – eg. retrieve only bits of data from a string or URL or delimiters
  • string replacement – eg on some IDE you can find and replace a string, use regex to search for particular patterns
  • web scraping – look for specific patterns for data to scrape

Sample Codes

Apex class that implements removal of white space not found in quotes

Python script that crawls pages that matches the pattern.

And finally, as a takeaway just learn the syntax and hack away.

How to Create a Generic Class for Mocking REST Callouts for Unit Test

I’m starting a new habit of posting regularly on my blog every week. I’ll be kicking it off with tips for creating a generic class or a mocking factory for mocking calls to an external third-party service.

Why do we need to do a mock?

When running unit tests the platform does not allow to do a callout to external dependencies. To test our code base we would need to mock the response as if calling the third party dependency.

By mocking we focus on the code being tested, isolating it from the state and behavior of the external system. The dependencies are simulated and the output state can be controlled.

To start we create a class that implements the HttpCalloutMock. This class enables sending a fake response when doing HTTP callouts. When our code makes a callout, the response will come from our HttpCalloutMock class.

When creating the class we define the constructor and parameters. We can make it generic and serve as a mock factory. Instead of writing several mock classes for every type of response, we only write it once which promotes code reusability best practices. And during unit testing, we define the mock response on the fly.

Here is our sample class which implements the HttpCalloutMock.

And if we have a class that does an HTTP Callout and we want to write a unit test for it. This is how it going to look like.

This is how we would create a unit test.

Key Takeaways

  • Use named credentials when possible when doing HTTP Callouts. Will talk about this more in the future.
  • When writing the unit test, the key is to call Test.setMock() which makes sure any callout from your code will return the Mock object.
  • Define the mock response on the fly to test different response.

Hope you find this useful. Stay tuned for more coding content and tips. If interested in the source code it is available in GitHub.

Takeaways From Creating My First IOS Mobile App

Sticking to the goals I’ve set this year I wanted to create a mobile app that even though small will add value to the users. I’ve been using similar existing apps that allow you to track the money you’ve saved so for a particular goal say for example a new motorbike, a vacation or a new house. Most of the apps have heaps of annoying ads and the pro version where bit overpriced IMHO. Scratching my own itch and being a software engineer that I am I studied how I can build my own app. Here are my notes and takeaways.

Key Learnings:

  • Download and install Xcode – grab it from the Appstore. Is the major tool for developing apps that run on the Mac platform.
  • Creating a
    • New Project
      • Choose a template for either iOS, watchOS, tvOS, macOS
    • Playground – allows to you write basic prototypes and quickly validate some of the standard classes and methods
  • Explore the User Interface – learn the basic shortcuts, customize fonts and preferences, use tabs, view documentation, create snippets
  • Start using Git as early as possible to get used to versioning your code
  • Based on the MVC design pattern – model is the database, the view is the UI and uses the controller to bridge the UI and model.
  • Learn the Interface Builder components – scenes, initial view, how to connect to view controllers, adding components to the scene
  • Learn pins and constraints – basically pinning an object to object or window on the layout
  • Learn how to compile and debug – work with schemas, use debugger, unit tests
  • Cocoa Touch classes – eg UITableViewController, UITableViewCell. Mostly extending the main UIViewController
    • Each class has its own stub methods implementation
    • Custom UITableViewCell
  • Using the First responder – is the current object receiving events, when using text fields you tell the object to resign itself so that it hides the keyboard.
    • You can also use events like touchesBegan when a user taps anywhere else and then call resign the first responder
    • Using delegates – events in the text fields can be handled by the main controller
    • on viewDidLoad
      • textField.delegate = self
  • Learn how to create UI elements using code – navigation menu, labels, buttons, etc.
    • using .frame, .center and CGFloat and CGRect for positioning elements
    • drawing and animating UI elements with CAShapeLayer and CABasicAnimation
  • Using Core Data – using manageObject and NSPersistentContainer to load data into the controller from your model
    • data modeling with attributes and relationships
    • creating, updating and deleting Core Data
  • Navigation controller – use for containers for view controllers that allows transitions from one another and manages the titles
    • learn segue, identifiers and how to pass data from one view to another
    • unwinding segue
  • Know the concepts of instantiating nil – basically, you need to check that a particular instance of an object is not empty and only then can you use it in your logic else your application will crash
  • AppDelegate – handle application-wide events
  • Using UICollectiionView components –
    • UICollectiionViewDelegate – selecting and highlighting collection view elements
    • UICollectionViewDataSource – provides data and views required for the collection view
    • UICollectionViewDelegateFlowLayout – can be used to allow horizontal scrolling
  • Using Notification Center – use UNUserNotificationCenter
    • creating notifications using DateComponents and Calendar
  • Human Interface Guidelines
    • App icons need to be pixel perfect for all device types
    • If you going to have a launch screen make sure that is consistent or the transition is not abrupt
  • You can develop apps locally and to start distributing or testing it on a device you need to sign up for the Developer Program.
    • I needed to be on the developer program(cost $ 100USD yearly) before I can test on a device. I couldn’t figure out how to do it without one.
    • If you need the company name listed on the app store instead of the individual then you need to be in the DUNS sytem during registration. If not you can still do register for DUNS after you signed up. DUNS registration is free and processing takes about a couple of weeks. After that, you can email apple to change your account from individual to a company account.
  • Certificates, Identifiers, and Profiles – used for preparing your app for distribution. Create one for development and another one for release to production for the App Store
    • Download the certificates and import it to your project and assign the teams
  • AppStore Connect – use to submit your app and what will appear in the App Store listing
    • on Xcode archive and upload the app
    • check all the required fields and create screenshots of your app for an enticing listing on the App Store
    • Watch out for typos. I was rushing putting the free version in and made a dumb mistake on the naming.

So that was in summary what I did and there is still a whole lot of area that I didn’t need for my MVP. Sure enough, will start incorporating some more functionality on the app on future upgrades like using iCloud and security then share how I did this here on the blog and on my youtube channel.

My 2018 recap and 2019 plans

My first post of the year and what better way to kick off but by having a fresh new theme layout. I have lots of stuffs plan for the my blog this year so stay tune.

Anyway my 2018 was probably the busiest I have been as I reached new goals in terms of career and knowledge. I managed to knocked down Salesforce and integration certification one after another like dominoes. I’m now eligible to take the Salesforce Certified Technical Architect exam board.

These are the certifications I achieved for 2018.

  • Salesforce Certified Sharing and Visibility Designer
  • Salesforce Certified Application Architect
  • Salesforce Certified Data Architecture & Management Designer
  • Salesforce Certified Identity and Access Management Designer
  • Salesforce Certified System Architect
  • Salesforce Certified Development Lifecycle & Deployment Designer
  • Salesforce Certified Integration Architecture Designer
  • Salesforce Certified Platform Developer II
  • Salesforce Certified Field Service Lightning Consultant
  • Certified Mule 4 Developer
  • Certified Boomi Developer

But there is one hurdle, my weakness, my kryptonite.. my presentation skills lacks evoking confidence. (feedback from one of the senior manager). I need to up my game on my communication skills and be more engaged.

For 2019 I’m approaching stuffs a little differently. First off I need to fix my damn finances as I really let go on 2018. I barely invested, didn’t build assets and got myself into some debt( not huge) but I do not normally get into debts.

My mentality and approach this year is to build assets as well as upping my communication skills.

  • I’ll be starting a free series of Youtube tutorials for Salesforce Architecture, Mulesoft and web development – this should increase my subscribers and get me back on the Youtube Partner Program
  • I’ll start a paid course in Salesforce and Mulesoft
  • Not too serious approach on my merch that I sell in Amazon
  • Scratch my itch and build some mobile app
  • Build a Saas – brain dump my knowledge on CICD, etc.
  • Colloborate more and try to get Salesforce MVP status (how this is an asset I don’t know yet)

So basically anything that I do should lead to building an asset. It could be passive income projects, part time work to buy assets like real estate, stocks and crypto.