最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Restrict 0 at first digit in input textbox Angular8 - Stack Overflow

programmeradmin1浏览0评论

How can i restrict first digit as 0 in the input textbox which accepts numbers.

for example: Number cannot be like this 012345 Number can be like 123000

I have used pattern /^0|[^0-9.]/ but its not working in angular reactive forms. My Input textbox control looks like below:

<input type="text" class="form-control" id="inputNumber" formControlName="inputNumber" maxlength="5" minlength ="1" pattern="/^0|[^0-9.]/"   [(ngModel)]="inputNumber"  required>

Any thoughts are highly appreciated.

Thanks for help.

How can i restrict first digit as 0 in the input textbox which accepts numbers.

for example: Number cannot be like this 012345 Number can be like 123000

I have used pattern /^0|[^0-9.]/ but its not working in angular reactive forms. My Input textbox control looks like below:

<input type="text" class="form-control" id="inputNumber" formControlName="inputNumber" maxlength="5" minlength ="1" pattern="/^0|[^0-9.]/"   [(ngModel)]="inputNumber"  required>

Any thoughts are highly appreciated.

Thanks for help.

Share Improve this question asked Sep 4, 2020 at 4:58 user1989user1989 473 silver badges7 bronze badges 2
  • why using ngModel when us using formControlName – brk Commented Sep 4, 2020 at 5:03
  • I get value from database to show it dynamically in textbox. So i used ngmodel to display it. Incase i want to edit the text box my textbox should not allow first digit as zero. – user1989 Commented Sep 4, 2020 at 5:07
Add a ment  | 

2 Answers 2

Reset to default 6

Please use below pattern

[1-9][0-9]*

Sample code

<!DOCTYPE html>
<html>
    <body>
Only numbers not starting with zero allowed.<br>
        <input type="text" pattern="^[1-9][0-9]*$" required oninput="if(!this.value.match('^[1-9][0-9]*$'))this.value='';"></input>
    </body>
</html>

Use Reactive form & a custom validator with reactive form and check the value on change. This will give more control in handling the form. The below code shows two different error when the input starts with 0 or if it is not a number, It will also disable the form submit button any invalid input.

To populate the data in the input you can use setValue like done in populateValue function

import {
  Component,
  VERSION,
  OnInit
} from "@angular/core";
import {
  FormGroup,
  FormBuilder,
  FormControl,
  AbstractControl,
  ValidationErrors,
  ValidatorFn
} from "@angular/forms";

@Component({
  selector: "my-app",
  templateUrl: "./app.ponent.html",
  styleUrls: ["./app.ponent.css"]
})
export class AppComponent implements OnInit {
  myForm: FormGroup;

  constructor(private fb: FormBuilder) {}

  ngOnInit() {
    this.myForm = this.fb.group({
      myInput: ["", [this.customValidator]] // custom validator
    });
    this.populateValue();
  }

  populateValue() {
    // use this to populate input with api response
    this.myForm.controls.myInput.setValue("wwedwedwed");
  }

  customValidator(control: AbstractControl): ValidationErrors {
    let error = {
      name: "",
      message: ""
    };
    if (control.value !== "") {
      // this validation will check if the value does not start with 0 or !isNaN
      if (isNaN(control.value)) {
        error.name = "notNumber";
        error.message = "Cannot be a string";
        return error;
      }
      if (control.value.startsWith(0)) {
        {
          error.name = "noZeroStart";
          error.message = "Cannot start with 0";
          return error;
        }
      }
      return null;
    }
    return error;
  }
}
<form [formGroup]="myForm">
  <div>
    <input formControlName='myInput'>
    <div *ngIf="myForm.controls.myInput.errors">
      {{myForm.controls.myInput.errors.message}}
    </div>
  </div>
  <button type='submit' [disabled]="myForm.invalid">
 Submit</button>

</form>

Stackblitz Demo

发布评论

评论列表(0)

  1. 暂无评论