forms - 输入时没有表单标签的表单验证 - Angular 2

标签 forms angular tags

我有一个弹出组件,我想在其中为名称的输入元素插入表单验证(必填字段和最小长度为 3 个字符)。 如果不在表单标签中设置完整代码,是否可以做到这一点?

<div class="scenario-div">
<label style="font-size: 1.4rem; font-weight: 400; margin-bottom: 10px;">{{context.header}}</label>
<div class="" style="width: 90%; margin-bottom: 10px; align-self: center;">
    <div style="display: flex; flex-direction: column; margin-bottom: 10px;">
        <label style="font-size: 1.2rem; font-weight: 500;">Name</label>
        <div style="display:flex; flex-direction:row;">
            <input type="text" [(ngModel)]="context.name" placeholder="enter Name" style="color: #569bd2; margin: 0px; width: 50%" minlength="3" required/>

            <select *ngIf="context.showOptionDropdown" class="custom-select-project" style="width:50%" #optionSelect (change)="context.option.value">
                <option disabled>Select type</option>
                <option value="option1">option1</option>
                <option value="option2">option2</option>
                <option value="option3">option3</option>
                <option value="option4">option4</option>
            </select>
        </div>
    </div>

    <div style="display: flex; flex-direction: column; margin-bottom: 10px;" *ngIf="!context.hideDescription">
        <label style="font-size: 1.2rem; font-weight: 400;">Description</label>
        <textarea rows="4" [(ngModel)]="context.description" cols="50" maxlength="250" placeholder="Enter text here" style="color: #569bd2; resize: none; font-weight: 400; font-size: 1.2rem;"></textarea>
    </div>
</div>
<div>   
    <button class="btn-main" (click)="confirm(context)" style="width: 15%;">Confirm</button>
</div>

最佳答案

基于ngModel的'验证'

    <input type="text" required name="title" [(ngModel)]="titleModel">
    <span style="color:red" *ngIf="titleModel?.length > 10">
          10 max
    </span>
    <span style="color:red" *ngIf="!titleModel">
          required
    </span>
    <button [disabled]="titleModel?.length > 10 || !titleModel">OK</button>

DEMO


基于局部模板变量的“验证”:

<input type="text" (keyup)='0' #title>
<span style="color:red" *ngIf="title.value.length > 10">
      10 max
</span>
<span style="color:red" *ngIf="!title.value">
      required
</span>

<button [disabled]="title.value.length > 10 || !title.value">OK</button>

DEMO

关于forms - 输入时没有表单标签的表单验证 - Angular 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46905052/

相关文章:

javascript - 输入值/仅启用最后 10 个字符

php - 我怎样才能改进这段代码?

javascript - 如何访问 typescript 中的字段验证错误?

google-analytics - 访问 Google Analytics 时出现 "Resource not available. Please try again later"错误

git - git中如何使用标签管理软件版本

javascript - 按 ENTER 键填充表单并阻止表单提交

php - 尝试将数据加载到 ChoiceType 表单中,但没有保存

asp.net-mvc - 当我的表单方法是 POST 时,用户请求 GET

javascript - Angular 服务是否可以直接更改注入(inject)它的组件的属性(没有商店/RxJs)?

javascript - Angular 2 - 自定义表单控件 - 禁用