检查字符串是否仅包含数字和点(。)

时间:2019-09-04 09:11:59

标签: angular typescript

我需要使用一个字段作为字符串,并且我希望用户只能添加数字和点。而且我正在网上寻找并很难找到任何东西,任何人都可以帮忙我,我将非常感激。在此先感谢!!

7 个答案:

答案 0 :(得分:1)

如果您使用正则表达式进行检查,那就很好了。 请尝试下面的RegEx。

(?!0+$)^[0-9].*$

答案 1 :(得分:1)

不确定什么是正确的,什么不是。因此,我的示例测试了只有点,只有数字,它可以以零等开头的情况。

但是正则表达式可以做到这一点。

//编辑:根据评论更具体的正则表达式

var reg = new RegExp('^[0-9]+(\.[0-9]+)*$')
reg.test("0") // true
reg.test("0.") // false
reg.test("0.1") // true
reg.test("0...1.2") // false
reg.test("00.0.888.6") // true
reg.test(".0.8.6") // false
reg.test("01.2.a3") // false - there is "a"

答案 2 :(得分:1)

第一个为打字稿中的小数位创建的伪指令,如下所示:

import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
  selector: '[appDecimalNumber]'
})
export class DecimalNumberDirective {
  private regex: RegExp = new RegExp(/^\d*\.?\d*$/g);
  private specialKeys: Array<string> = ['Backspace', 'Tab', 'End', 'Home', '-', 'ArrowLeft', 'ArrowRight', 'Del', 'Delete'];
  constructor(private el: ElementRef) {
  }
  @HostListener('keydown', ['$event'])
  onKeyDown(event: KeyboardEvent) {
    console.log(this.el.nativeElement.value);
    // Allow Backspace, tab, end, and home keys
    if (this.specialKeys.indexOf(event.key) !== -1) {
      return;
    }
    let current: string = this.el.nativeElement.value;
    const position = this.el.nativeElement.selectionStart;
    const next: string = [current.slice(0, position), event.key == 'Decimal' ? '.' : event.key, current.slice(position)].join('');
    if (next && !String(next).match(this.regex)) {
      event.preventDefault();
    }
  }
}

在您的app.module.ts中插入指令。在您的html中使用如下指令:

<input type="textbox" [(ngModel)]="InputValue" appDecimalNumber>

答案 3 :(得分:1)

在按键事件中调用此函数并传递事件。我也在我的项目中使用此功能,并且效果很好。

numberOnlyWithFloat(event): boolean {
  const charCode = (event.which) ? event.which : event.keyCode;
  console.log("charCode ::: ", charCode);
  if (charCode == 46) {
    console.log("true...");
    return true;
  }
  if (charCode > 31 && (charCode < 48 || charCode > 57)) {
    return false;
  }
  return true;
}

答案 4 :(得分:1)

// Imports the Google Cloud client library
import com.google.cloud.speech.v1.RecognitionAudio;
import com.google.cloud.speech.v1.RecognitionConfig;
import com.google.cloud.speech.v1.RecognitionConfig.AudioEncoding;
import com.google.cloud.speech.v1.RecognizeResponse;
import com.google.cloud.speech.v1.SpeechClient;
import com.google.cloud.speech.v1.SpeechRecognitionAlternative;
import com.google.cloud.speech.v1.SpeechRecognitionResult;
import com.google.protobuf.ByteString;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

public class QuickstartSample {

  /**
   * Demonstrates using the Speech API to transcribe an audio file.
   */
  public static void main(String... args) throws Exception {
    // Instantiates a client
    try (SpeechClient speechClient = SpeechClient.create()) {

      // The path to the audio file to transcribe
      String fileName = "./resources/audio.raw";

      // Reads the audio file into memory
      Path path = Paths.get(fileName);
      byte[] data = Files.readAllBytes(path);
      ByteString audioBytes = ByteString.copyFrom(data);

      // Builds the sync recognize request
      RecognitionConfig config = RecognitionConfig.newBuilder()
          .setEncoding(AudioEncoding.LINEAR16)
          .setSampleRateHertz(16000)
          .setLanguageCode("en-US")
          .build();
      RecognitionAudio audio = RecognitionAudio.newBuilder()
          .setContent(audioBytes)
          .build();

      // Performs speech recognition on the audio file
      RecognizeResponse response = speechClient.recognize(config, audio);
      List<SpeechRecognitionResult> results = response.getResultsList();

System.out.println("size "+results.size()); //SIZE IS ZERO

      for (SpeechRecognitionResult result : results) {
        // There can be several alternative transcripts for a given chunk of speech. Just use the
        // first (most likely) one here.
        SpeechRecognitionAlternative alternative = result.getAlternativesList().get(0);
        System.out.printf("Transcription: %s%n", alternative.getTranscript());
      }
    }
  }
}

答案 5 :(得分:1)

我建议您使用regex来验证字符串。以下正则表达式仅允许数字和。

/[^.0-9]+/g

我只想验证数字,然后可以使用以下表达式。

/[^0-9]+/g

随时提问...

答案 6 :(得分:1)

注意:所有仅使用模式的解决方案,仍然允许,让用户键入受限制的符号,然后将其标记为无效。

如果您想防止输入无效字符,则可以使用下面的解决方案。

该组件甚至不允许输入数字和点以外的任何其他字符,
并在将字符插入到输入中之前始终确保输入是数字。

此外,不允许使用这些字符键入无效的数字,例如“ 45..3”,“ 3.4..4”。
奖励功能1:在移动设备上可以正常使用(因为不查找Keydown / Keyup事件)。
额外功能2:它也不允许复制粘贴无效的文本。

import { Component, Input, forwardRef } from '@angular/core';

import {
  NG_VALUE_ACCESSOR,
  NG_VALIDATORS,
  Validator,
  FormControl,
  ValidationErrors,
  ControlValueAccessor
} from '@angular/forms';

@Component({
  selector: 'numeric-input',
  template: '<input type="text" inputmode="numeric" [placeholder]="placeHolderText" [ngModel]="inputValue" (input)="onInputChange($event)">',
  providers: [
  {
    provide: NG_VALUE_ACCESSOR,
    useExisting: forwardRef(() => NumericInputComponent),
    multi: true
  },
  {
    provide: NG_VALIDATORS,
    useExisting: forwardRef(() => NumericInputComponent),
    multi: true
  }]
})
export class NumericInputComponent implements ControlValueAccessor, Validator {
  @Input() public placeHolderText = '';
  @Input() public isRequired = false;

  public inputValue: string;

  public onInputChange(event: any): void {
    const newValue = event.target.value;
    if (!this.isValidInput(newValue)) {
      // Invalid input detected. Resetting to previous value
      event.target.value = this.inputValue;
    } else if (newValue !== this.inputValue) {
      // New valid input detected.
      this.inputValue = newValue;
      this.propagateChange(this.inputValue);
    }
  }

  //#region Custom validation

  // Note: Used the mechanism described in the link below
  // https://medium.com/@tarik.nzl/angular-2-custom-form-control-with-validation-json-input-2b4cf9bc2d73

  // Called for setting the initial value
  public writeValue(value: string): void {
    if (this.isValidInput(value) && this.inputValue !== value) {
      this.inputValue = value;
    }
  }

  // Validates the form, returns null when valid else the validation object
  public validate(formControl: FormControl): ValidationErrors {
    return (this.isRequired && !this.inputValue) ? { required: true } : null;
  }

  // Registers function that will be fired when changes are made.
  public registerOnChange(callbackFunction: (newValue: string) => void): void {
    this.propagateChange = callbackFunction;
  }

  // Non-implemented method which are required by the validator interface
  public registerOnTouched(callbackFunction: () => void): void { }

  // The method set in registerOnChange to emit changes back to the form
  private propagateChange = (newValue: string) => { };

  private isValidInput(value: string): boolean {
    // Note: ParseInt is not recommended as it will convert "222aa" -> "222" and assume as valid
    return !isNaN(Number(value));
  }

  //#endregion Custom validation
}

用法:

<numeric-input [(ngModel)]="ModelNameHere">
</numeric-input>

注意:您可以考虑将component.ts文件之外的组件的html模板移出以分离html文件,而改用templateUrl(就像在下面的示例中所做的那样)。

这里是快速进行code sampledemo的快速注视,以防万一。
这里是sample用于角材料。