Angular 6-验证器模式不起作用

时间:2018-09-28 19:05:53

标签: angular

我正在使用角度为6的反应形式,并尝试对密码字段进行一些验证。基本上,它必须超过8个字符,至少包含1个大写字母,并且至少包含1个符号。

我测试过的正则表达式为^(?=.*[A-Z])(?=.*[!@#\$%\^&\*])(?=.{9,})

这是我的登录组件ts的摘录:

  ngOnInit() {
        this.loginForm = this.formBuilder.group({
            userName: ['Username', [Validators.required]],
            password: ['Password', [Validators.pattern("^(?=.*[A-Z])(?=.*[!@#\$%\^&\*])(?=.{9,})")]]            
        });
    }

这是我的表单组div:

 <div class="form-group">
                      <input type="password" formControlName="password" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.password.errors }" />
                      <div *ngIf="submitted && f.password.errors" class="invalid-feedback">              
                          <div *ngIf="f.password.errors.pattern">Password must contain more than 8 characters, 1 upper case letter, and 1 special character</div>
                      </div>
                  </div>

基本上,即使密码看起来正确,密码也不会生效。任何提示将不胜感激。

5 个答案:

答案 0 :(得分:6)

ng模式似乎采用regExp作为参数(例如angularJs):

Validators.pattern(new RegExp("^(?=.*[A-Z])(?=.*[!@#\$%\^&\*])(?=.{9,}))")

您也可以使用/..../

Validators.pattern(/^(?=.*[A-Z])(?=.*[!@#\$%\^&\*])(?=.{9,})/)

应该工作;)

答案 1 :(得分:1)

<?php

$name = $_POST['name'];
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
$phone = $_POST['phone'];

if (!empty($name) || !empty($username) || !empty($password) || !empty($email) || !empty($phone)) {

    $host = "localhost:80";
    $dbUsername = "root";
    $dbPassword = "";
    $dbname = "pracdata";


    //create connection
    $conn = new mysqli($host, $dbUsername, $dbPassword, $dbname);
    if (mysqli_connect_error()) {
     die('Connect Error('. mysqli_connect_errno().')'. mysqli_connect_error());
    } else {
     $SELECT = "SELECT email From users Where email = ? Limit 1";
     $INSERT = "INSERT Into users (name, username, password, email, phone) values(?, ?, ?, ?)";


     //Prepare statement
     $stmt = $conn->prepare($SELECT);
     $stmt->bind_param("s", $email);
     $stmt->execute();
     $stmt->bind_result($email);
     $stmt->store_result();
     $rnum = $stmt->num_rows;

     if ($rnum==0) {
      $stmt->close();
      $stmt = $conn->prepare($INSERT);
      $stmt->bind_param("ssssii", $username, $username, $password, $email, $phone);

      $stmt->execute();
      echo "Your account has been registered!";
     } else {
      echo "This email is already linked to Preak account";
     }
     $stmt->close();
     $conn->close();
    }
} else {
 echo "All fields are required";
 die();
}
?>

答案 2 :(得分:0)

我认为这是由于HTML中的*ngIf条件造成的。]

尝试*ngIf="loginForm.controls.password.hasError('pattern')"

答案 3 :(得分:0)

您需要在模式中使用/.../并添加所需的验证器,这是工作示例https://stackblitz.com/edit/angular-rkxs3q

的链接
<h1 class="title">validation</h1>

<hr/>

<form class="user-form" [formGroup]="userForm" (submit)="onSubmit()">

<div class="form-group">
    <label for="type">User type:</label>
    <select id="type" formControlName="type">
  <option disabled value="null">please select user type</option>
  <option *ngFor="let userType of userTypes">{{userType}}</option>
</select>
</div>

<div class="form-group">
    <label for="name">User Name:</label>
    <input type="text" id="name" formControlName="name" />
</div>



<div class="form-group">
    <label for="address">User  address:</label>
    <input type="text" id="address" formControlName="address" />
</div>

<div class="form-group">
    <label for="password">password:</label>
    <input type="text" id="password" formControlName="password" />
</div>
 <div class="error"
 *ngIf="!userForm.get('password').valid && userForm.get('password').touched">
Password must contain more than 8 characters, 1 upper case letter, and 1 
special 
character
</div>

 <button type="submit">submit</button>
   </form>
   <hr/>

打字稿

import { Component, OnInit, OnDestroy } from '@angular/core';
import { FormBuilder, FormGroup, Validators, ValidatorFn, FormControl, 
 ValidationErrors } from '@angular/forms';
 import { Subscription } from 'rxjs';
import { Observable } from 'rxjs';



 @Component({
 selector: 'my-app',
 templateUrl: './app.component.html',
 styleUrls: ['./app.component.css']
  })
 export class AppComponent implements OnInit {
 userForm: FormGroup;
  userTypes: string[];

 private userTypeSubscription: Subscription;

 constructor(private fb: FormBuilder) { }

  ngOnInit() {
this.userTypes =["Custumer","Admin","Super Admin"]
 this.userForm = this.fb.group({
  type: [null, [Validators.required]],
  name: [null, [
    Validators.required,
    Validators.pattern(/^[A-z0-9]*$/),
    Validators.minLength(3)]
  ],
  address: null,
  password: [null, [
    Validators.required,Validators.pattern(/^(?=.*[A-Z])(?=.*[!@#\$%\^&\*])(?=. 
     {9,})/)]
  ]
});
  }
 }

答案 4 :(得分:0)

如果要验证数值,请

检查输入的类型属性。 如果是数字类型输入,那么某些浏览器将不会将任何非数字值传递给验证器,因此,如果您在验证器数组中声明了Validators.required,则地图中将出现必需的错误。