how to handle dynamic regex value for input type inside ngFor?

Viewed 300

I have an array of objects with each object having details of the input field which has to be generated dynamically, I have done the dynamical input field generation based on the type received from API, but I'm not able to match the regular expression.

 <ng-container *ngFor="let list of inputList">
    <label>{{list.key}}</label>
    <input [type]="list.type" [value]="list.value" [required]="list.required" [pattern]="list.regex"  (input)="valueChange($event)"  />
    </ng-container>

Api response inputList

[{key: "Name", type: "text", value: "", required: true, mandatory: false, regex: [A-Z][a-z]$}
{key: "Number", type: "number", value: "", required: true, mandatory: false, regex: [0-9]{10}$}
{key: "description", type: "textarea", value: "", required: true, mandatory: false, regex: [a-z]{10,250}}
{key: "email", type: "text", value: "", required: true, mandatory: false, regex: /\S+@\S+\.\S+/}];

However the pattern is not working is there any alternative only to accept these inputs from keyboard, for example in case of mobile user should not be able to type other keys except number.

1 Answers

It should work if you pass the regex as a string and not including the /, like this:

[{key: "Name", type: "text", value: "", required: true, mandatory: false, regex: "[A-Z][a-z]$"}
{key: "Number", type: "number", value: "", required: true, mandatory: false, regex: "[0-9]{10}$"}
{key: "description", type: "textarea", value: "", required: true, mandatory: false, regex: "[a-z]{10,250}"}
{key: "email", type: "text", value: "", required: true, mandatory: false, regex: "\S+@\S+\.\S+"}]

<form onsubmit="return false;">
  <input type="text" pattern="[A-Z][a-z]$">
  <input type="submit">
</form>

On the other hand, Are you sure these are the regex you want to validate these fields?

[A-Z][a-z]$ - An upper case and a lower case letter, exactly those two. Maybe you meant something like [A-Z][a-z]+ (one upper case, any number of lower case letters).

[0-9]{10}$ - Exactly ten digits.

[a-z]{10,250} - Between 10 and 250 lower case letters with no spaces or points.

\S+@\S+\.\S+ - For email validation there are great examples and in depth discussion here.

Related