Verify the input in a Text field by considering intricate rules and the position of characters

As a newcomer to the world of Angular and java script, I find myself faced with the challenge of validating a Reactive form Text field under certain conditions.

The conditions are:

  1. The length of the input value should be between 7 and 25 characters.
  2. Valid input can consist of Alphanumeric values along with an Asterisk (*) for wildcard characters. Any other special characters entered into the text field will be deemed invalid.
  3. An Asterisk(*) is only allowed as input from the 5th to the 13th position. Anything beyond that is considered invalid. For example: 8500*001001… (Invalid) 8500* (valid)

    I have some knowledge in writing simple custom validations. If you have any suggestions or solutions, please do not hesitate to share. Thank you in advance.

Answer №1

If you're familiar with regex patterns, utilizing Validators.pattern is one way to validate input. However, creating a custom validator can be more manageable and easier to understand compared to using a complex regex pattern. With a custom validator, you have the ability to provide tailored error messages for validation issues. Essentially, a custom validator is a function that either returns an object if the validation fails or null if it succeeds.

Implementing a custom validator for reactive forms:

import { AbstractControl, ValidationErrors } from "@angular/forms"

export const inputTextValidator = function inputTextValidator(control: AbstractControl): ValidationErrors | null {

  let getErrorObject = function (message): ValidationErrors {
    return {
      inputText: true,
      message // customized error message related to the validation rule
    }
  }

  let value: string = control.value || '';

  // Checking if the value's length falls within a specific range, e.g., 7-25 characters
  if (value.length < 7 && value.length < 25) {
    return getErrorObject(`The text length must be between 7-25, current length: ${value.length}`);
  }

  // Validating for invalid characters such as #$%^%$^/-+
  let validCharacters = /^[a-zA-Z0-9\*]+$/g
  if (validCharacters.test(value) === false) {
    return getErrorObject(`The text contains invalid characters, current value: ${value.length}`);
  }

  let asterisk = /^\w+\*?$/g
  if (asterisk.test(value) === false) {
    return getErrorObject(`Only one asterisk is allowed at the end of the string, current value: ${value.length}`);
  }

  // Verifying the position of the asterisk at 8th-13th index
  let indexOfAsterisk: number = value.indexOf('*'); // zero-based index
  if (indexOfAsterisk >= 0 && (indexOfAsterisk < 8 || indexOfAsterisk > 12)) {
    return getErrorObject(`Asterisk must be positioned at 8-13, current * position: ${indexOfAsterisk}`);
  }

  return null;
}

The example you provided suggests starting the asterisk from the 5th position, conflicting with the minimum value length criteria. Hence, I ensured that the minimum length requirement is at least 8 characters in order to address this discrepancy.

Here is a StackBlitz example for reference

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Transforming a Java byte array into a ReactJS video: Step-by-step guide

I am getting a file from a Java API server and need to convert it into a video using React JS. The Java API server converts the video file into a byte array using Files.readAllBytes(file) and I need to use this video file byte array to create a video fil ...

I am experiencing difficulties with broadcasting and attending events

File.js scope.menuItemClick = function (def, callbackText, keepMenuOpen) { console.log(def); if(def.automationId === "Print"){ console.log("before send"); $scope.$root.$broadcast("printingData","my Data"); console.log("after send"); } Nex ...

Vue.js is unable to recognize this type when used with TypeScript

In my code snippet, I am trying to set a new value for this.msg but it results in an error saying Type '"asdasd"' is not assignable to type 'Function'. This issue persists both in Visual Studio and during webpack build. It seems like Ty ...

What is the process for linking a Python Flask CAS server with an Angular application?

After successfully setting up the python server (Flask to be specific) and establishing a successful connection to my CAS server, it is working flawlessly by redirecting to CAS login and returning accurate user data upon login. Here is the relevant code sn ...

Creating custom generic functions such as IsAny and IsUnknown that are based on a table of type assignability to determine

I attempted to craft a generic called IsAny based on this resource. The IsAny generic appears to be functioning correctly. However, when I implement it within another generic (IsUnknown), it fails: const testIsUnknown2: IsUnknown<any> = true; // iss ...

Do null and undefined fall under other types as subcategories in Typescript?

As I was exploring some old code, I came across the following snippet: let isNew: boolean = null let myName: string = undefined This snippet seems to indicate that in typescript, a variable of type boolean can accept null and a variable of type string can ...

Unable to generate the 'validator' property on the string 'userForm' while utilizing the component factory

Currently, I am in the process of creating a component factory to generate my login form dynamically. Initially, I encountered an issue where the FormGroup was not recognized by the form where I was introducing my component. After resolving that with the h ...

Leverage the pre-defined Ionic Sass variables for optimal styling

Is it possible to utilize existing Sass Variables in Ionic 5 for our custom CSS classes? The specific variables I am referring to can be found here: https://ionicframework.com/docs/v3/theming/overriding-ionic-variables/ I'm interested in creating som ...

An issue has been identified with the functionality of the router-out

Issue with Router Loading Component Outside of the router-outlet in app.component.ts @Component({ selector : "body", template : `<router-outlet></router-outlet>`, directives: [ROUTER_DIRECTIVES] }) @RouteConfig([ {path: "/aut ...

Utilizing Angular Firestore in Combination with Await

Upon reviewing this response, I attempted to implement async/await with a firestore call but it seems like I may be overlooking something. The aim is to fetch a collection of 'hex' documents for a hex grid using Snapshot. Initially, I had valueC ...

How is it possible for this for loop to function properly without the need to pass the incrementing variable

I managed to compile my code and it's working fine, but there's something interesting - the variable that should reference the incrementing value is not included as an argument in the for loop. var _loop2 = function _loop2() { var p = docume ...

Resizing svg to accommodate a circle shape

As I work on my vue.js app that involves a plethora of diverse icons, I made the decision to create a small icons builder in node.js. The purpose is to standardize their usage and also "crop" each SVG so it fits perfectly within its parent container by uti ...

A peculiar TypeError occurred when testing a React component with Enzyme, preventing the addition of a property as the object is not extensible in the Object

Encountered a peculiar issue during testing where I am trying to merge two objects to use as the style of a component, replicating the component's logic with the code provided below. var styles = { "height": 20 } var expectedStyles = (Object as any). ...

Error message: "Vue3 JSX files are throwing a ReferenceError because React is not defined."

Currently, I am working on integrating storybook with antdv. However, when importing a tsx file that contains jsx within the button.stories.js file, I encountered an error stating "ReferenceError: React is not defined". You can view the error here. It is i ...

Steps for making a "confirm" button within a modal that includes a redirect URL

I have developed a modal that, upon clicking on the confirm button, should redirect the user to the page titled securities-in-portfolio. modal <div class="modal-footer justify-content-center"> <button type="button" class ...

The application within the Main Module is not being acknowledged by the other components within the module

I am facing an issue with my AngularJS application where the directive I created within the 'FormTest' module is not recognizing the variable 'app' even though it is defined within the same module. The error message I receive is TS2304 ...

Separate your HTML code and move it to a different HTML document within Angular CLI

Is there a way to extract my HTML section from the file app.compontent.ts and place it in a separate HTML document? I've tried adding the HTML code directly into the generated class app.component.ts but it doesn't seem to work. I'd also lik ...

Firebase Integrations: How to Handle Errors in External API Calls within Firebase Functions

My current challenge involves retrieving data from an external API using Firebase functions and displaying it in an Angular application hosted on Firebase. Billing is enabled for the project. The API call works fine on localhost, but fails to fetch data wh ...

Is there a way to define type information for a global variable when utilizing dynamic import within a function?

Here is a simplified version of my server code: server.ts import google from "googleapis"; const androidPublisher = google.androidpublisher("v3"); app.use('something', function(req, res, n){ ... }) ...(only one of the dozens of other meth ...

Integrate additional attributes into the interface object in TypeScript on-the-fly without modifying the existing class

I'm faced with a situation where I cannot modify the class below. export class Cars implements Vehicales { color?: string; type?: string[]; } The templates object is passed to kendoReactGrid which contains column strings, and I need to add a ...