Validate Regex Input. Segregate Records In Database. Do REST Callout. Display Datatable
- abhyash
- Mar 11, 2023
- 4 min read
Prepared By: Abhyash Timsina – 11 March 2023
Overall Solution: A Lightning Web Component where a South African ID number can be entered to see if the year of birth has any significant public holidays
Acceptance Criteria:
· A website containing an input field for entering an ID number
· A search button that will carry out the "Search" operation
· The search button ought to be turned off until a correct ID number is entered.
· The article listed below, which explains how to validate an ID number, must be used to determine the validity of the ID number -https://www.westerncape.gov.za/generalpublication/decoding-your-south-african-id-number-0
· If an invalid ID number is entered, a notification or prompt ought to appear.
· A database table should only contain legitimate ID number searches.
· The ID number itself need to serve as a special reference for next revisions.
· Date of Birth, Gender, and SA Citizen information must be stored against the ID number record in the database together with the decoded information.
· Every time a visitor searches with the same SA ID number, a counter on the record needs to be increased.
· To obtain a list of banking and public holidays, use the Calendarific API (https://calendarific.com/api-documentation) after saving or modifying the ID record.
· The visitor should see a list of all banking and public holidays on the page.

Source Code for SearchSouthAFricanIDNumber Apex Class
/**
* Created by Abhyash Timsina on 11/3/2023.
*/
public with sharing class SearchSouthAfricanIDNumber {
public class PublicHolidayList
{
@AuraEnabled
public String name {set;get;}
@AuraEnabled
public String description {set;get;}
@AuraEnabled
public String date_Z {set;get;}
}
@AuraEnabled(Cacheable=true)
public static List<South_African_Id_Searches__c> searchSAId(String idNumber) {
return [
SELECT Id, ID_Number__c, Gender__c, Date_Of_Birth__c, SA_Citizen__c, Counter__c
FROM South_African_Id_Searches__c
WHERE ID_Number__c =: idNumber
LIMIT 1
];
}
@AuraEnabled
public static void updateSAId(String idNumber) {
South_African_Id_Searches__c saRecord = [SELECT Id, ID_Number__c, Counter__c FROM South_African_Id_Searches__c WHERE ID_Number__c =: idNumber LIMIT 1];
Decimal currentCounter = saRecord.Counter__c;
saRecord.Counter__c = currentCounter + 1;
System.debug('NEW COUNTER: ' + saRecord.Counter__c);
try {
update saRecord;
} catch (Exception e) {
throw new AuraHandledException(e.getMessage());
}
}
@AuraEnabled
public static South_African_Id_Searches__c createRecMethod(South_African_Id_Searches__c rec){
try {
insert rec;
return rec;
} catch (Exception e) {
throw new AuraHandledException(e.getMessage());
}
}
@AuraEnabled(Cacheable=true)
public static List<PublicHolidayList> getPublicHolidays(Integer dobYear) {
List<PublicHolidayList> holidaysByDate = new List<PublicHolidayList>();
Calendarific_c mc = Calendarific_c.getValues(data_set_name);
try {
HttpRequest req = new HttpRequest();
HttpResponse res = new HttpResponse();
Http http = new Http();
req.setHeader('Content-Type', 'application/json');
req.setHeader('X-Accept-Version', '2.0.0');
req.setEndpoint('https://calendarific.com/api/v2/holidays?&api_key=********&country=ZA&year=' + dobYear);
req.setMethod('GET');
res = http.send(req);
JSON2APEX obj = JSON2APEX.parse(res.getBody());
for(JSON2APEX.Holidays holiday : obj.response.holidays){
if (holiday.primary_type == 'Public Holiday') {
PublicHolidayList phl = new PublicHolidayList();
phl.name = holiday.name;
phl.description = holiday.description;
phl.date_Z = String.valueOf(holiday.date_Z.iso);
holidaysByDate.add(phl);
}
}
} catch (Exception e) {
System.debug('Error:' + e.getMessage() + 'LN:' + e.getLineNumber());
}
return holidaysByDate;
}
}
Source Code for southAfricanIDSearch Lightning Web Component
<!--
- Created by Abhyash Timsina on 11/3/2023.
-->
<template>
<lightning-card>
<lightning-layout multiple-rows="true" vertical-align="end">
<lightning-layout-item size="4" padding="around-small">
<!--Input text to Search Account-->
<lightning-input type="text" data-id="saIdInput" label="Enter South African ID Number"
value={searchId}
onchange={checkIdValid}
pattern="(([0-9]{2})(0|1)([0-9])([0-3])([0-9]))([ ]?)(([0-9]{4})([ ]?)([0-1][8]([ ]?)[0-9]))"
message-when-pattern-mismatch="Please enter a valid South African ID Number"
message-when-value-missing="Please enter a value">
</lightning-input>
</lightning-layout-item >
<lightning-layout-item size="2" padding="around-small">
<!--Search Button-->
<lightning-button label="Search" variant="brand" disabled={validity} onclick={checkPublicHolidays}>
</lightning-button>
</lightning-layout-item>
<lightning-layout-item size="4" padding="around-small">
Purpose: Check if there are any important public holidays on my year of birth
</lightning-layout-item>
<div style="height: 300px;">
<lightning-datatable
key-field="id"
data={publicHolidayRecords}
columns={columns}>
</lightning-datatable>
</div>
</lightning-layout>
</lightning-card>
</template>
/**
* - Created by Abhyash Timsina on 11/3/2023.
*/
import {LightningElement, track} from 'lwc';
import searchSAId from '@salesforce/apex/SearchSouthAfricanIDNumber.searchSAId';
import updateSAId from '@salesforce/apex/SearchSouthAfricanIDNumber.updateSAId';
import getPublicHolidays from '@salesforce/apex/SearchSouthAfricanIDNumber.getPublicHolidays';
import createRecMethod from '@salesforce/apex/SearchSouthAfricanIDNumber.createRecMethod';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
const columns = [
{ label: 'Name', fieldName: 'name', fixedWidth: 150 },
{ label: 'Date', fieldName: 'date_Z', fixedWidth: 120},
{ label: 'Description', fieldName: 'description', fixedWidth: 500},
];
export default class SouthAfricanIDSearch extends LightningElement {
@track validity = true;
@track southAfricanId;
@track gender = '';
@track dob = '';
@track dobYear = '';
@track citizen = '';
@track counter = '';
@track publicHolidaysList = [];
columns = columns;
@track publicHolidayRecords;
records;
error;
checkIdValid(event) {
this.southAfricanId = event.target.value;
const idFromInput = this.template.querySelector('lightning-input[data-id="saIdInput"]');
if (idFromInput.checkValidity() === true) {
this.validity = false;
}
else this.validity = true;
}
checkPublicHolidays() {
console.log('ID FROM INPUT: ' + this.southAfricanId);
searchSAId({ idNumber: this.southAfricanId })
.then((result) => {
console.log('RESULT: ' + JSON.stringify(result));
this.records = result;
this.error = undefined;
if (JSON.stringify(result) === '[]') {
console.log('CREATED');
this.createSARecord();
this.retrievePublicHolidays();
}
if (JSON.stringify(result) !== null) {
console.log('UPDATED');
this.updateSARecord();
this.retrievePublicHolidays();
}
})
.catch((error) => {
this.error = error;
this.records = undefined;
});
}
retrievePublicHolidays() {
if (this.southAfricanId.substring(0, 1) === '0') {
this.dobYear = '20' + this.southAfricanId.substring(0, 2);
console.log('DOB after 2000: ' + this.dobYear);
}
else if (this.southAfricanId.substring(0, 1) === '9') {
this.dobYear = '19' + this.southAfricanId.substring(0, 2);
console.log('DOB before 2000: ' + this.dobYear);
}
getPublicHolidays({ dobYear: this.dobYear })
.then((result) => {
this.publicHolidayRecords = result;
console.log('PUBLIC HOLIDAY RESULTS: ' + result);
this.error = undefined;
})
.catch((error) => {
this.error = error;
this.publicHolidayRecords = undefined;
});
}
updateSARecord() {
updateSAId({ idNumber: this.southAfricanId })
.then((result) => {
this.records = result;
this.error = undefined;
})
.catch((error) => {
this.error = error;
this.records = undefined;
});
}
createSARecord() {
const dobDigits = this.southAfricanId.substring(0, 6);
console.log('DOB Digits: ' + dobDigits);
this.dob = dobDigits.substring(4, 6) + '/' + dobDigits.substring(2, 4) + '/' + dobDigits.substring(0, 2);
console.log('DOB: ' + this.dob);
const genderDigits = this.southAfricanId.substring(7,11);
console.log('Gender Digits: ' + genderDigits);
if (genderDigits < 4999 ) {
this.gender = 'Female';
}
else if (genderDigits >= 5000) {
this.gender = 'Male';
}
console.log('Gender: ' + this.gender);
const citizenDigits = this.southAfricanId.substring(10,11);
console.log('Citizen Digits: ' + citizenDigits);
if (citizenDigits === '0' ) {
this.citizen = 'SA Citizen';
}
else if (citizenDigits === '1') {
this.citizen = 'Permanent Resident';
}
console.log('Citizen: ' + this.citizen);
this.saRecord = {
ID_Number__c : this.southAfricanId,
Gender__c : this.gender,
Date_Of_Birth__c : this.dob,
SA_Citizen__c : this.citizen,
Counter__c: +1
}
createRecMethod({ rec : this.saRecord })
.then(result => {
this.message = result;
this.error = undefined;
if(this.message !== undefined) {
this.saRecord.ID_Number__c = '';
this.saRecord.Gender__c = '';
this.saRecord.Date_Of_Birth__c = '';
this.saRecord.SA_Citizen__c= '';
this.saRecord.Counter__c= '';
this.dispatchEvent(
new ShowToastEvent({
title: 'Success',
message: 'New Search Record created',
variant: 'success',
}),
);
}
console.log(JSON.stringify(result));
console.log("result", this.message);
})
.catch(error => {
this.message = undefined;
this.error = error;
this.dispatchEvent(
new ShowToastEvent({
title: 'Error creating record',
message: error.body.message,
variant: 'error',
}),
);
console.log("error", JSON.stringify(this.error));
});
}
}
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>56.0</apiVersion>
<description>South African ID Search</description>
<isExposed>true</isExposed>
<masterLabel>South African ID Search</masterLabel>
<targets>
<target>lightning__HomePage</target>
<target>lightning__AppPage</target>
</targets>
</LightningComponentBundle>
Outcome:



Comments