Get 2024 Templates Mega Bundle!14 Bootstrap, Vue & React Templates + 3 Vector Sets
Get for 99$

Inquiry Regarding Input Validation in Angular Metronic


Hello dear devs,

I hope this message finds you well. I've been exploring Angular Metronic and had a question I was hoping you could assist me with.

I'm looking to implement input validation and formatting for employee worked hours in my Angular application. The input field should allow users to enter time in the format 'hh:mm', such as '08:00'. I would like to ensure that the inputted time is in the correct format and potentially perform additional checks or transformations on the entered value. Could you provide some insights or best practices on how to achieve this within Angular Metronic?

Any assistance or advice you can offer on this matter would be greatly appreciated. Thank you in advance for your time and expertise. I eagerly await your insights.

Best regards,
Savio Lenvica


Text formatting options
Submit
Here's a how to add some HTML formatting to your comment:
  • <pre></pre> for JS codes block
  • <pre lang="html"></pre> for HTML code block
  • <pre lang="scss"></pre> for SCSS code block
  • <pre lang="php"></pre> for PHP code block
  • <code></code> for single line of code
  • <strong></strong> to make things bold
  • <em></em> to emphasize
  • <ul><li></li></ul>  to make list
  • <ol><li></li></ol>  to make ordered list
  • <h3></h3> to make headings
  • <a></a> for links
  • <img> to paste in an image
  • <blockquote></blockquote> to quote somebody
  • happy  :)
  • shocked  :|
  • sad  :(

Replies (3)


Hello Savio,

Implementing input validation and formatting for hours in your Angular application can be achieved using Angular's built-in features along with some custom logic. Here's a general approach you can take:

Input Validation: Use Angular's reactive forms to create a form control for the employee worked hours input field. You can then use Angular's validators to ensure that the input is in the correct format 'hh:mm'. For example, you can use a custom validator function to check the format:


import { FormControl, Validators } from "@angular/forms";

const timeFormatValidator = (control: FormControl) => {
const valid = /^\d{2}:\d{2}$/.test(control.value);
return valid ? null : { invalidFormat: true };
};

const hoursControl = new FormControl("", [
Validators.required,
timeFormatValidator
]);


Input Formatting: You can use Angular's input event to format the input as the user types. For example, you can automatically insert the colon ':' after the first two digits:


formatTimeInput(input: HTMLInputElement) {
const value = input.value.replace(/\D/g, "");
if (value.length > 2) {
input.value = `${value.slice(0, 2)}:${value.slice(2, 4)}`;
} else {
input.value = value;
}
}


And in your template:


<input type="text" (input)="formatTimeInput($event.target)">


Additional Checks/Transformations: Depending on your requirements, you can add additional checks or transformations to the entered value. For example, you can convert the entered time to a standard format for consistency.


convertToStandardFormat(time: string): string {
const [hours, minutes] = time.split(":");
const formattedHours = hours.padStart(2, "0");
const formattedMinutes = minutes.padStart(2, "0");
return `${formattedHours}:${formattedMinutes}`;
}


You can then use this function to transform the entered value before saving it.
I hope this helps! Let me know if you have any further questions or need clarification on any part.



Hello,

Thank you for your detailed response and guidance on implementing input validation and formatting for employee worked hours in Angular. I appreciate the effort you put into providing a thorough explanation and code examples.

However, upon further consideration, I realized that my initial requirement may not have been fully clear. Allow me to clarify:

While the provided solution addresses the validation and formatting of time input in the 'hh:mm' format, I would like to introduce an additional constraint specific to my application.

In our scenario, the user may enter time values representing the number of hours worked by an employee. For example, the user might input '830' to indicate 8 hours and 30 minutes worked. In such cases, I would like the input field to automatically format the value as '8:30', treating the input as a time value rather than a duration.

Additionally, to prevent unrealistic or invalid time entries, I would like to impose a limit of 24 hours for the entered value. This means that users should not be able to input more than 24 hours of work time.

Could you please provide guidance on how to modify the input validation and formatting logic to accommodate these requirements? Specifically, I am looking for a solution that automatically formats the entered value as 'hh:mm' and enforces the 24-hour limit.

Your assistance in addressing this additional constraint would be greatly appreciated.

Thank you for your understanding and support.

Best regards,
Savio Lenvica



Modify the formatTimeInput function to handle both formats and enforce the 24-hour limit:

formatTimeInput(input: HTMLInputElement) {
let value = input.value.replace(/\D/g, "");

if (value.length === 3) {
// Convert "hhmm" to "hh:mm"
const hours = value.slice(0, -2);
const minutes = value.slice(-2);
value = `${hours}:${minutes}`;
}

// Ensure the hours are limited to 24
const [hours, minutes] = value.split(":");
const totalHours = parseInt(hours, 10) + parseInt(minutes, 10) / 60;
const formattedHours = Math.min(totalHours, 24).toString().padStart(2, "0");
const formattedMinutes = (totalHours % 1 * 60).toString().padStart(2, "0");

// Format the value as "hh:mm"
input.value = `${formattedHours}:${formattedMinutes}`;
}


Update the timeFormatValidator function to handle both formats and enforce the 24-hour limit:

const timeFormatValidator = (control: FormControl) => {
const valid = /^(?:\d{1,2}:?\d{2}|\d{3})$/.test(control.value);

if (!valid) {
return { invalidFormat: true };
}

const [hours, minutes] = control.value.split(/<img alt="shocked" src="https://devs.keenthemes.com/assets/media/smiles/shocked.png">(?<=\d)(?=\d{2}$)/);
const totalHours = parseInt(hours, 10) + parseInt(minutes, 10) / 60;

if (totalHours > 24) {
return { invalidTime: true };
}

return null;
};


Update your template to include the new validation logic and formatting on the input event:

<input type="text" (input)="formatTimeInput($event.target)" [formControl]="hoursControl">
<div *ngIf="hoursControl.invalid && (hoursControl.dirty || hoursControl.touched)">
<div *ngIf="hoursControl.errors?.invalidFormat">Invalid time format. Please use "hh:mm" or "hhmm" format.</div>
<div *ngIf="hoursControl.errors?.invalidTime">Invalid time. Please ensure the total hours are less than or equal to 24.</div>
</div>


Text formatting options
Submit
Here's a how to add some HTML formatting to your comment:
  • <pre></pre> for JS codes block
  • <pre lang="html"></pre> for HTML code block
  • <pre lang="scss"></pre> for SCSS code block
  • <pre lang="php"></pre> for PHP code block
  • <code></code> for single line of code
  • <strong></strong> to make things bold
  • <em></em> to emphasize
  • <ul><li></li></ul>  to make list
  • <ol><li></li></ol>  to make ordered list
  • <h3></h3> to make headings
  • <a></a> for links
  • <img> to paste in an image
  • <blockquote></blockquote> to quote somebody
  • happy  :)
  • shocked  :|
  • sad  :(
Text formatting options
Submit
Here's a how to add some HTML formatting to your comment:
  • <pre></pre> for JS codes block
  • <pre lang="html"></pre> for HTML code block
  • <pre lang="scss"></pre> for SCSS code block
  • <pre lang="php"></pre> for PHP code block
  • <code></code> for single line of code
  • <strong></strong> to make things bold
  • <em></em> to emphasize
  • <ul><li></li></ul>  to make list
  • <ol><li></li></ol>  to make ordered list
  • <h3></h3> to make headings
  • <a></a> for links
  • <img> to paste in an image
  • <blockquote></blockquote> to quote somebody
  • happy  :)
  • shocked  :|
  • sad  :(