简体   繁体   English

如何验证 Angular 2 中的输入

[英]How to validate an input in Angular 2

I have an input place and I want this input to have length from 3 to 7 and not allow special characters.我有一个输入位置,我希望这个输入的长度从 3 到 7 并且不允许特殊字符。

<input  required maxlength="7" minlength="3" class="plate"  type="text"  #a>

I tried this but I want to print a message just when I leave the input place whithout having filling it properly我试过了,但我想在我离开输入位置时打印一条消息而没有正确填写

You can add the pattern attribute with an appropriate regex pattern, like this:您可以使用适当的正则表达式模式添加模式属性,如下所示:

pattern="[A-Za-z0-9]{3,7}"模式="[A-Za-z0-9]{3,7}"

Full input example:完整输入示例:

 <input required class="plate" type="text" pattern="[A-Za-z0-9]{3,7}" #a>

To validate the input:要验证输入:

for simplicity, you can use input:invalid CSS selector:为简单起见,您可以使用 input:invalid CSS 选择器:

 <input required class="plate" type="text" pattern="[A-Za-z0-9]{3,7}" #a> <span class="validation-msg">Not Valid</span>.validation-msg { display: inline-block; } input:invalid { color: red; } input:invalid ~.validation-msg { display: inline-block; }

or for something powerful use template form.或用于功能强大的模板表单。 https://angular.io/guide/forms https://angular.io/guide/forms

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM