为睫毛膏创建一个管道,用于输入文本示例00.00

时间:2018-08-14 22:01:30

标签: javascript html angular

我正在尝试为输入文字创建一个弯角管道4,在输入时应在字符之间插入一个点。

输入内容包含4个字符,并且必须通过除以4个字符来输入点。

例如,0000应该显示为00.00

这已经完成,但是如果我粘贴一个大于4个字符的值,我将不允许并保留该字段为空。

管道

import {Pipe, PipeTransform} from "@angular/core";

@Pipe({name: 'tarifa'})
export class TarifaPipe implements PipeTransform{

    transform(value: string): string {

        if (!value) {
            return '';
        }

        var tarifaValor = value.replace(/\D/g, '');

        if (tarifaValor.length !== 4) {
            return value;
        }

        var tarifaLista = tarifaValor.match(/^(\d{2})(\d{2})$/);

        if (tarifaLista && tarifaLista.length === 3) {
            value = tarifaLista[1] + '.' + tarifaLista[2];
        }

        return value;
    }
}

2 个答案:

答案 0 :(得分:0)

import {Pipe, PipeTransform} from "@angular/core";

@Pipe({name: 'tarifa'})
export class TarifaPipe implements PipeTransform{

 transform(value: string): string {
    //since you want to set it to '' when input value is > 4 chars.
    if (!value || value.length !== 4 || value.match(/^[0-9]+$/) == null) {
        return '';
    } else {
        var tarifaValor = value.replace(/\D/g, '');
        //you need to change your previous regex from `/^(\d{2})(\d{2})$/` to make it work for value with length 2,3,4.
        //if the input value is not always restricted to 4 you can use regex /^(\d{0,2})(\d{2})$/ and change above if cond `value.length > 4`
        var tarifaLista = tarifaValor.match(/^(\d{2})(\d{2})$/);
      if (tarifaLista && tarifaLista.length === 3) {
        value = tarifaLista[1] + '.' + tarifaLista[2];
      }
    }
    return value;
  }
}

对于value = 234,输出将为2.34
对于值= 2345,输出将为23.45
对于值= 23456,输出将为

您可以利用HTML输入的maxlength属性来限制输入字段最多接受4个字符。 maxlength="4"

答案 1 :(得分:0)

您可以使用padStart来确保字符串始终为4位数字,并使用parseInt来删除填充后的填充,例如:

transform(value: string): string {

    var tarifaValor = value.replace(/\D/g, '');

    // if it is blank or over 4 digits, return blank
    if (tarifaValor.length < 1 || tarifaValor.length > 4) {
        return '';
    }

    // Pad with zeros to make 4 digits:
    tarifaValor = tarifaValor.padStart(4, '0');

    var tarifaLista = tarifaValor.match(/^(\d{2})(\d{2})$/);

    // Use parseInt on first match to trim leading zeros.
    value = parseInt(tarifaLista[1]).toString() + '.' + tarifaLista[2];

    return value;
}

结果:

对于值= 1,输出将为0.01

对于值= 12,输出将为0.12

对于值= 123,输出将为1.23

对于值= 1234,输出将为12.34

对于value = 12345,输出将为