[英]Angular2 Forms Validation Error messages
I am new to Angular and JavaScript overall, I'm trying to add messages when user input is wrong using the Materialize library (the data-error attribute). 我是Angular和JavaScript的新手,我尝试使用Materialize库(data-error属性)在用户输入错误时添加消息。 So my html component looks like this: 所以我的html组件看起来像这样:
<input
type="text"
id="username"
formControlName="username"
[class.valid]="username?.valid && username.dirty"
[class.invalid]="!username?.valid && username.dirty && !username.pending"
>
<label for="username"
data-error="ERROR_MESSAGE" // <-- this is what I need to work
>Username</label>
I want to change the data-error attribute depending on the error present. 我想根据当前错误更改data-error属性。 Right now it will print "ERROR_MESSAGE" on any error present. 现在,它将在出现任何错误时打印“ ERROR_MESSAGE”。 I tried writing a function and binding it with [attr.data-error] like this: 我试着编写一个函数并将其与[attr.data-error]绑定,如下所示:
displayUsernameErrorMessage() {
let message = '';
let usernameError = this.username.errors;
if(usernameError.pattern){
message = "Invalid Username"
console.log(usernameError);
}
else {
return null;
}
}
I think I'm doing a really bad job with this, the function logs like 10 times in the console and it's a poor solution. 我认为我的工作做得很糟糕,该功能在控制台中的日志记录为10次,这是一个糟糕的解决方案。 Any ideas on how to make it work better are greatly appreciated! 任何有关如何使其更好地工作的想法都将受到赞赏!
EDIT 1: Additional info is that I want to display different messages depending on the error. 编辑1:其他信息是我想根据错误显示不同的消息。 So if I get an error from the Validator.pattern - I want the message to be something like "Invalid username" or if it's from Validators.required - "Please insert a username", something like that. 因此,如果从Validator.pattern收到错误消息-我希望该消息类似于“无效的用户名”,或者是来自Validators.required-“请插入用户名”,则类似这样。
That's how I'm doing it (adapted to your Exemple): 这就是我的做法(适应您的示例):
<form name="nameForm" [formGroup]="nameForm">
<fieldset>
<label for="username">Username</label>
<input
required
id="username"
formControlName="username"
>
<span
class="text-danger"
[hidden]="nameForm.controls.name.valid || itemForm.controls.name.pristine"
>
<small>{{'Please enter your name'}}</small>
</span>
</fieldset>
</form>
In your TS file : 在您的TS文件中:
import { FormGroup, FormBuilder, FormControl, Validators } from '@angular/forms';
export class InputComponent {
public nameForm: FormGroup;
constructor(private formBuilder: FormBuilder) {
this.nameForm = this.formBuilder.group({
username: new FormControl('', Validators.required),
});
}
//... codes..
}
Where you can customize the text-danger
in your CSS
(or any alternative) file 您可以在其中自定义CSS
(或任何其他替代文件)中的text-danger
I needed to do something like this as well so I ended up writing a directive that can be placed on <label>
elements. 我也需要做这样的事情,所以我最终写了一条可以放在<label>
元素上的指令。
In your example it would look like this: 在您的示例中,它看起来像这样:
<label for="username" errorMessageForFormControl>Username</label>
<input required id="username" formControlName="username">
I wanted to avoid repeating the control name twice so the directive looks at the value of the for
attribute and finds the control from that. 我想避免重复两次控件名称,因此该指令查看for
属性的值并从中查找控件。 If your FormControls and <input>
field IDs happen to not match up you can set it yourself. 如果您的FormControls和<input>
字段ID恰好不匹配,则可以自己进行设置。
<label for="somethingDifferent" errorMessageForFormControl="username">Username</label>
<input required id="somethingDifferent" formControlName="username">
The directive ended up looking like this: 该指令最终看起来像这样:
import { Directive, Host, HostBinding, Input, Optional, OnInit, SkipSelf } from '@angular/core';
import { AbstractControl, ControlContainer } from '@angular/forms';
@Directive({
selector: '[errorMessageForFormControl]'
})
export class errorMessageDirective implements OnInit {
@HostBinding('class.validation-error') validationErrorCssClass = false;
@HostBinding('attr.data-error') errorMessage: string = null;
@Input() public errorMessageForFormControl: string;
@Input() public for: string;
private ctrl: AbstractControl = null;
constructor(
@Optional() @Host() @SkipSelf()
private controlContainer: ControlContainer
) { }
public ngOnInit(): void {
if (!this.controlContainer) {
return;
}
const formControlName = this.errorMessageForFormControl || this.for;
if (formControlName) {
this.ctrl = this.controlContainer.control.get(formControlName);
}
if (this.ctrl) {
this.ctrl.statusChanges.subscribe(statusText => {
if (statusText === 'INVALID') {
// invalid
const errors = this.ctrl.errors;
if (errors) {
const errKey = Object.keys(errors)[0];
const errVal = errors[errKey];
this.errorMessage = errVal === true ? errKey : errVal;
} else {
this.errorMessage = 'validation failed';
}
this.validationErrorCssClass = true;
} else {
// valid
this.errorMessage = null;
this.validationErrorCssClass = false;
}
});
}
}
}
And you can refer to the data-error attribute in some css 您可以在某些CSS中引用data-error属性
[data-error].validation-error::after {
color:red;
content: attr(data-error);
opacity: 0.8;
font-weight: bold;
font-style: italic;
font-size: 0.75em;
margin-right: 0.25em;
z-index: 99;
float: right;
transform: translateY(85%);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.