【问题标题】:Angular: Validation pattern not to allow any space in input formcontrolAngular:验证模式不允许输入表单控件中的任何空间
【发布时间】:2020-12-18 16:20:42
【问题描述】:

我在 Angular2 中使用了 formcontrol,并希望添加验证模式以不允许输入中根本没有“空格”。如何做到这一点?

类似问题:How to add Validation pattern not to allow only space in input Angular2?

【问题讨论】:

标签: angular typescript angular10


【解决方案1】:

您可以在输入字段中添加正则表达式模式以不包含空格。我在我的 Angular 应用程序中的密码输入字段上没有使用空格验证。请看一下。

HTML

<input
 type="password"
 class="pass"
 ngModel
 placeholder="Password"
 [pattern]="noSpacesRegex"
 name="password"
 matInput
 required
 #passwordInput="ngModel"
/>

正则表达式变量:

const noSpacesRegex = /.*\S.*/;

【讨论】:

    【解决方案2】:
     formInitialization() {
        this.forbiddenRules = FORBIDDEN_WORD_RULE();
        this.forbiddenWordForm = this.fb.group({
          'forbiddenWordName': ['', [
            Validators.required,
            Validators.pattern(this.forbiddenRules.FORBIDDEN_WORD_PATTERN),
            Validators.minLength(this.forbiddenRules.MIN_LENGTH), Validators.maxLength(this.forbiddenRules.MAX_LENGTH)]],
          
            'forbiddenWordReplaceWord': ['', [
              Validators.required,
              Validators.pattern(this.forbiddenRules.FORBIDDEN_WORD_PATTERN),
              Validators.minLength(this.forbiddenRules.MIN_LENGTH), Validators.maxLength(this.forbiddenRules.MAX_LENGTH)]],
    
          'action':  ['', [Validators.required]],
          'forbiddenWordStatus': [this.forbiddenWordStatus === 'Active' ? true : false],
        });
      }
    
    
    export const FORBIDDEN_WORD_RULE = () => {
      return {
      'FORBIDDEN_WORD_PATTERN': `[${getUniCode()}&,-]+(\\s[${getUniCode()}&,-]+){0,}?`,
      'KEYPRESS_FORBIDDEN_GROUP': `/^[${getUniCode()}&,_\- ]+$/`,
      'MIN_LENGTH': 2,
      'MAX_LENGTH': 50,
      'RESOLUTION': {
        'RESOLUTION_WIDTH': 0,
        'RESOLUTION_HEIGHT': 0
       }
      };
    };
    

    【讨论】:

    • 您也可以为表单控件提供答案吗?谢谢,我可以送积分
    【解决方案3】:

    之前的所有答案都是正确的。 您可以制作自定义验证器并在表单控件中使用它。 首先为示例创建一个文件名: custom.validator.ts,您可以将其添加到文件夹名称验证器中

    import { AbstractControl, ValidationErrors } from '@angular/forms';
      
    export class CustomValidator {
        static cannotContainSpace(control: AbstractControl) : ValidationErrors | null {
            if((control.value as string).indexOf(' ') >= 0){
                return {cannotContainSpace: true}
            }
      
            return null;
        }
    }
    

    在您的 Component .ts 文件中,您的表单在哪里,您可以执行以下操作:

    import { Component } from '@angular/core';
    import { FormGroup, FormControl, Validators} from '@angular/forms';
    import {CustomValidator } from './validators/custom.validator';
      
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent {
      form = new FormGroup({
        username: new FormControl('', [Validators.required,CustomValidator.cannotContainSpace]),
       
      });
       
      get f(){
        return this.form.controls;
      }
        
      submit(){
        console.log(this.form.value);
      }
    }
    

    最后在 html 模板中:

    <form [formGroup]="form" (ngSubmit)="submit()">
       
        <div class="form-group">
            <label for="username">Username</label>
            <input 
                formControlName="username"
                id="username" 
                type="text" 
                class="form-control">
            <div *ngIf="f.username.touched && f.username.invalid" class="alert alert-danger">
               
                <div *ngIf="f.username.errors.cannotContainSpace">Username can not contain space.</div>
            </div>
        </div>
        
        
        <button class="btn btn-primary" type="submit">Submit</button>
    </form>
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-08-17
      • 2011-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多