I'm setting up form validation in the UI for one of our projects. One of the text boxes needs to have a differing validation pattern
based on the selection of a previous dropdown. For example, if the dropdown selection is name
, the pattern should be:
pattern='[a-zA-Z ]+'
where as if it is number
, it should be:
pattern='[0-9 ]+`
I've setup a function in the component to set up a validation string based on that selection:
fields: string[] = [];
validationPattern: string;
private validationType(field: string[]) {
if (field.includes('number')) {
this.validationPattern = '[0-9]+';
return this.validationPattern;
} else if (field.includes('name')) {
this.validationPattern = '[a-zA-Z1-9][a-zA-Z0-9 ]+';
return this.validationPattern;
}
}
And in the HTML, I have the following. setField is a function to actually choose the field; validationType is what I'm trying to use to create the validation pattern for the input:
<div ngbDropdownMenu>
<button
*ngFor="let selected of fields"
class="dropdown-item"
(click)="setField(selected); validationType(selected)">
{{ selected }}
</button>
</div>
And here is the input the form validation is on:
<input
type="text"
id="value"
name="value"
placeholder="Value"
#value1="ngModel"
pattern=this.validationPattern
[(ngModel)]="profile.value">
I have two issues so far:
How can I properly pass either the value of the validationPattern variable or the output of the validationType() function to pattern in the input? As of right now, it seems to be reading
this.validationPattern
as the actual pattern - that is, the wordsthis.validationPattern
and not the associated value. No matter if I select name or number, anything I type in is invalid.How can I use validationType() outside of the click? I've been told it is very bad practice to have more than one function associated to a (click), and in this particular case, it should be reserved for setField().