Angular 6限制某些字母

时间:2018-09-12 10:27:57

标签: angular typescript angular-material

我有以下输入字段。我试图只允许用户从A-F输入字母。如果用户尝试输入超出范围的字母,则该字母应被即时修整,即没有按钮可以验证其有效输入。输入字段还允许数字和特殊字符。

<mat-form-field>
  <input matInput (keyup)="MACAddressInput()" placeholder="MAC address" name="mac_address" required [(ngModel)]="model.mac_address" (blur)="validate()">
  <mat-error *ngFor="let error of errors_by_field['mac_address']">{{error.message}}</mat-error>
</mat-form-field>

  MACAddressInput() {
    if (this.model.mac_address) {
      const inputColon = this.model.mac_address.replace(new RegExp(':', 'g'), '').trim();
      const MAC_blocks = inputColon.match(/.{1,2}/g);
      let formatedMac = MAC_blocks.shift();
      for (const block of MAC_blocks) {
       formatedMac = formatedMac + ':' + block;
      }
      this.model.mac_address = formatedMac.toUpperCase();
    }
  }

我尝试使用html模式,但它允许用户输入任何内容

2 个答案:

答案 0 :(得分:2)

您可以创建一个custom pipe

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

@Pipe({
    name: 'myCustomPipe'
  })
  export class MyCustomPipe implements PipeTransform {
    transform(input: string): string {
        let newString = "";
      for(let i=0; i<= input.length; i++){
        var char = input.charAt(i);
        if(char.charCodeAt(0) >= 65 && char.charCodeAt(0) <=70){
            newString += char;
        }
      }

      return newString;
    }
  }

然后将其添加到您的模块中

 declarations: [
    ...
    MyCustomPipe,
    ...
]

以这种方式将其调用到您的.html组件中

{{ myText | myCustomPipe }}

我已经进行了测试,myText = "ABCG";用管道将文本修剪为ABC

要发挥功能的魔力:

if (this.model.mac_address) {
    let newString = "";
    for(let i=0; i<= this.model.mac_address.length; i++){
        var char = this.model.mac_address.charAt(i);
        if(char.charCodeAt(0) >= 65 && char.charCodeAt(0) <=70){
            newString += char;
        }
    }
    this.model.mac_address = newString.toUpperCase();
}

答案 1 :(得分:2)

如果您想使用简单的绑定功能

代码

    11-09-2018 14:57:50.579 [pool-14-thread-32] ERROR c.a.m.c.c.ChannelMessageCommand.execute - Error while converting JSON to object
javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: could not prepare statement
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1692)
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1602)
    at org.hibernate.jpa.internal.StoredProcedureQueryImpl.execute(StoredProcedureQueryImpl.java:224)
    at com.asite.message.channel.entity.service.ChannelService.getUserAccessibleDCs(ChannelService.java:619)
    at com.asite.message.channel.entity.service.ChannelService$$FastClassBySpringCGLIB$$ab52f291.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:738)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:673)
    at com.asite.message.channel.entity.service.ChannelService$$EnhancerBySpringCGLIB$$303bc2d0.getUserAccessibleDCs(<generated>)
    at com.asite.message.session.service.channel.ChannelSessionService.setChannelUserAccessibleDCs(ChannelSessionService.java:1140)
    at com.asite.message.command.channel.ChannelMessageCommand.execute(ChannelMessageCommand.java:112)
    at com.asite.message.command.channel.ChannelMessageCommand.execute(ChannelMessageCommand.java:44)
    at com.asite.message.TextMessageProcessor.lambda$executeMessageCommand$77(TextMessageProcessor.java:95)
    at com.asite.message.TextMessageProcessor$$Lambda$80/1154803940.run(Unknown Source)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.hibernate.exception.GenericJDBCException: could not prepare statement
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:47)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:109)
    at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$StatementPreparationTemplate.prepareStatement(StatementPreparerImpl.java:182)
    at org.hibernate.engine.jdbc.internal.StatementPreparerImpl.prepareStatement(StatementPreparerImpl.java:78)
    at org.hibernate.procedure.internal.ProcedureCallImpl.buildOutputs(ProcedureCallImpl.java:395)
    at org.hibernate.procedure.internal.ProcedureCallImpl.getOutputs(ProcedureCallImpl.java:363)
    at org.hibernate.jpa.internal.StoredProcedureQueryImpl.outputs(StoredProcedureQueryImpl.java:234)
    at org.hibernate.jpa.internal.StoredProcedureQueryImpl.execute(StoredProcedureQueryImpl.java:217)
    ... 21 common frames omitted
Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: The connection is closed.
    at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:206)
    at com.microsoft.sqlserver.jdbc.SQLServerConnection.checkClosed(SQLServerConnection.java:724)
    at com.microsoft.sqlserver.jdbc.SQLServerConnection.prepareCall(SQLServerConnection.java:2990)
    at com.microsoft.sqlserver.jdbc.SQLServerConnection.prepareCall(SQLServerConnection.java:2593)
    at sun.reflect.GeneratedMethodAccessor228.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.apache.tomcat.jdbc.pool.ProxyConnection.invoke(ProxyConnection.java:126)
    at org.apache.tomcat.jdbc.pool.JdbcInterceptor.invoke(JdbcInterceptor.java:108)
    at org.apache.tomcat.jdbc.pool.interceptor.AbstractCreateStatementInterceptor.invoke(AbstractCreateStatementInterceptor.java:75)
    at org.apache.tomcat.jdbc.pool.JdbcInterceptor.invoke(JdbcInterceptor.java:108)
    at org.apache.tomcat.jdbc.pool.DisposableConnectionFacade.invoke(DisposableConnectionFacade.java:81)
    at com.sun.proxy.$Proxy93.prepareCall(Unknown Source)
    at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$1.doPrepare(StatementPreparerImpl.java:86)
    at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$StatementPreparationTemplate.prepareStatement(StatementPreparerImpl.java:172)
    ... 26 common frames omitted

HTML

MACAddressInput(e) {
   let code = e.key.charCodeAt(0);
   if ((code >= 65 && code <= 90) || (code >= 97 && code <= 122)) {}
   else {
     e.preventDefault();
     return;
   }
}

注意:确保您使用<input matInput (keydown)="MACAddressInput($event)" placeholder="MAC address" name="mac_address" required [(ngModel)]="model.mac_address" (blur)="validate()"> 事件。该代码将允许A-Z和a-z。