I am trying to check whether after I submit, login form without username / password, I will receive an error message below the certain field, and i done a simple test scenario for that:
it('password input should display required message', async() => {
component.validateForm.controls['password'].setValue('');
const submitBtn = el.querySelector("[data-test='submit']") as HTMLElement;
const control = el.querySelector("[data-test='password-control']") as HTMLElement;
submitBtn.click();
fixture.detectChanges();
expect(control.innerText).toContain('Please input your Password!');
});
html code:
<form nz-form [formGroup]="validateForm" class="login-form" (ngSubmit)="submitForm()" data-test="form">
<nz-form-item >
<nz-form-control nzErrorTip="Please input your username!" data-test="username-control">
<nz-input-group nzPrefixIcon="user" >
<input type="text" nz-input formControlName="username" placeholder="Username"/>
</nz-input-group>
</nz-form-control>
</nz-form-item>
<nz-form-item>
<nz-form-control nzErrorTip="Please input your Password!" data-test="password-control">
<nz-input-group nzPrefixIcon="lock">
<input type="password" nz-input formControlName="password" placeholder="Password" />
</nz-input-group>
</nz-form-control>
</nz-form-item>
<div nz-row class="login-form-margin">
<div nz-col [nzSpan]="12">
<label nz-checkbox formControlName="remember">
<span>Remember me</span>
</label>
</div>
<div nz-col [nzSpan]="12">
<a class="login-form-forgot">Forgot password</a>
</div>
</div>
<button nz-button class="login-form-button login-form-margin" [nzType]="'primary'" data-test="submit">Log in</button>
Or
<a>register now!</a>
</form>
and when I tried this in browser by running in dev tools after submiting form without typing anything in password input
document.querySelector("[data-test='password-control']").includes('Please input your Password!') it returns true, I also tried adding to code above tick(1000), before expect statement to make sure, there is enough time to make it appear before the check, but it hasn't changed anything, the test result is negative with message Expected '' to contain 'Please input your Password!'..
Will be happy with any suggestions to solve that issue :)
Related
html code:
<div id="1" class="grid-item"> <input type="text" size=1px value=""></div>
After entering the value in input section,i want to access the contents what i have enetered.
can anyone please help me in this question.
i didn't quite understand what you meant but i assume you meant the following ?
let input = document.getElementById('input')
let h1 = document.getElementsByTagName('h1')[0]
input.addEventListener('input', () => {
h1.textContent = input.value
})
<div id="1" class="grid-item"> <input type="text" size=1px value="" id='input'> <h1></h1></div>
Requires JavaScript or BackEnd But if you don't mind I will explain the javascript
...............
First, choose a unique identifier for your input, for example "MyInput":\
<div>
<input type="text" id="MyInput" value="">
</div>
It doesn't matter where it is ( form , input and ... )
Now let's go to JavaScript:( I attach it to a sticker )\
<a onclick=" alert( document.getElementById('MyInput').value ) "> Show Value Input</a>
You may not understand what this command is
I'm just referring to the onclick input
With the "alert" command the browser will show you something and if you know js, you know this
The document.getElementById command takes an ID and finds that tag, which you can access by typing a dot followed by the entry name.
For example, when you write something in your input, the input is a value and the fog is filled with that value.
From now on, every time you click on the a tag, you will be shown the input value
Complete code:
<div>
<input type="text" id="MyInput" value="">
</div>
<a onclick=" alert( document.getElementById('MyInput').value ) "> Show Value Input</a>
If you have any questions, send me an email:
amp.it.ir.go#gmail.com
;-)
I have an input tag..
<form name="patientSearchForm">
<input name="text" id="textType" type="text" class="form-control" />
<button type="submit">Submit Form</button><br /><br />
</form>
How to display the message that input field cant be empty using ng-if.
I am using
<span style="color:Red" ng-if="!textType.value" ng-show="patientSearchForm.$submitted"> My message </span>
But it is not working . Please help.
You are using angular forms a little differently!
First you need to create a form in the component.ts file, add a formcontrol to it. Use it in the HTML and then you can check for errors!
// In component.ts file,
someForm = new FormGroup({
someFormControl: new FormControl('')
});
// In HTML file
<div [formGroup]="someForm">
<input
name="someFormControl"
formControlName="someFormControl"
placeholder="Sample Input text"
/>
// Use ngIf directive here to check the value
<span *ngIf="!someForm.controls.someFormControl.value">
My error message
</span>
// The exclamation point will check if there is a value or not. if a value is there, that error message wont be shown; but if there is no value in the input field, this error will be shown
</div>
Try this
<input name="text" id="textType" type="text" class="form-control" />
<span class="form-control-feedback" *ngIf="textType.value.length === 0">
My message message
</span>
Error:
Cannot read property errors of null in form group.
I am creating a reactive form with some validation but i'm getting this error.Below is my whole form control
<div class="container mt-5">
<form
[formGroup] = 'loginForm'
(ngSubmit) = 'onSubmit()'
>
<div class="form-group">
<label>User Name</label>
<input
type="text" class="form-control"
placeholder="Enter User Name"
formControlName = "userName"
[ngClass]="{'is-invalid': (
loginForm.get('userName').dirty &&
!loginForm.get('userName').valid
)}"
>
<span class="invalid-feedback">
<span *ngIf = "loginForm.get('firstName').errors?.required">
Please Enter User Name.
</span>
</span>
</div>
<div class="form-group">
<label>Password</label>
<input
type="password"
class="form-control"
placeholder="Password"
formControlName = "password"
>
</div>
<button
type="submit"
class="btn btn-primary"
[disabled] = "!loginForm.valid">Submit</button>
</form>
{{loginForm.valid}}
Looking at your code, the possible reason for this error seems like you are accessing the firstName formcontrol when it is not defined in the loginForm.
It seems that you have gonna wrong with the formControlName, either it is not added in .ts file or by mistake you have mentioned 'firstName' in the error span
Replace firstName with userName in the error span
Please replace this code -
<span *ngIf = "loginForm.get('firstName').errors?.required">
Please Enter User Name.
</span>
With
<span *ngIf = "loginForm.get('userName').errors?.required"> // Here is the change
Please Enter User Name.
</span>
OMG, one hour working on it, realized I had
this.ContactInfoFG.get('phoneNumberFG') as FormGroup;
instead of
this.contactInfoFG.get('phoneNumberFG') as FormGroup;
Just check the characters for this issue nothing else!
Your solutions helped as well.
I have a form which validates all the inputs. For, say, 'username' input I want to make sure it's a required field first and second that its length isn't less than 2 or more than 10 (or fits another pattern I use).
I'd like to show an error when either validation fails. How do I do this if I want to show a specific error for each case case? For example: if the input is empty show 'required', if the value is wrong show 'invalid'. Here's my code:
component:
companyNamePattern = "^[a-z0-9_-]{8,15}$";
pwdPattern = "^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\s).{6,12}$";
emailPattern = "^[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,4}$";
this.addCompForm = fb.group({
'companyName': [null,Validators.compose([Validators.required,Validators.minLength(5),Validators.maxLength(20)])],
'companyPassword': [null,Validators.compose([Validators.required,Validators.minLength(5),Validators.maxLength(20)])],
'companyEmail': [null,Validators.compose([Validators.required,Validators.email])]
})
html:
<form [formGroup] ="addCompForm" (ngSubmit) = "addCompany(addCompForm.value)">
<p>Enter the company name:</p>
<input type="text" formControlName="companyName" >
<div class="alert" *ngIf="!addCompForm.controls['companyName'].valid && addCompForm.controls['companyName'].touched" >{{nameAlert}}</div>
<p>Enter the company password:</p>
<input type="text" formControlName="companyPassword">
<div class="alert" *ngIf="!addCompForm.controls['companyPassword'].valid && addCompForm.controls['companyPassword'].touched " >{{passAlert}}</div>
<p>Enter the company email:</p>
<input type="text" formControlName="companyEmail">
<div class="alert" *ngIf="!addCompForm.controls['companyEmail'].valid && addCompForm.controls['companyEmail'].touched " >{{emailAlert}}</div>
<br>
<br>
<div class="btn-container">
<button type="submit" [disabled]="!addCompForm.valid">
<i class="material-icons">done</i>
</button>
</div>
</form>
*ngIf="addCompForm.get('companyName').hasError('required')
add this to make required field and
*ngIf="addCompForm.get('companyName').hasError('minLength')
add this for making minLength and same as for max length .hasErro('maxlength')
I have worked on AngularJs and now working on Angular2. Whenever I searched for form validation in angular I always found the submit button like below:
In AnglarJs
<input type="submit"
ng-disabled="myForm.user.$dirty && myForm.user.$invalid ||
myForm.email.$dirty && myForm.email.$invalid">
In Angular2
<button type="submit" class="btn btn-default"
[disabled]="!heroForm.form.valid">Submit</button>
But I wanted the submit button should be enable and whenver user click on that we prompt the error below the text fields. There is no exact solution mentioned for this purpose.
I found some of that some of the users directly clicks on submit button and they wanted to fill only required fileds.
This is my observation only may be some of you also experienced the same while development.
For AngularJs 1 I am using custom-submit directive from here
https://gist.github.com/maikeldaloo/5133963
So please suggest me any solution to provide custom-submit in angular2 also.
---- Sample Login Form (Angular2) ---
<form class="ui large form" (ngSubmit)="onUserLogin(loginForm.form.valid)" #loginForm="ngForm" method="post" novalidate>
<sm-loader [complete]="!formSubmited" class="inverted" text="Loading..."></sm-loader>
<div class="field">
<input type="email" name="email" placeholder="Email" [(ngModel)]="login.email" #email="ngModel" required />
<div [hidden]="email.valid || email.pristine" class="error text-left">
Email is required
</div>
</div>
<div class="field">
<input type="password" name="password" placeholder="Password" [(ngModel)]="login.password" #password="ngModel" required />
<div [hidden]="password.valid || password.pristine" class="error text-left">
Password is required
</div>
</div>
<button class="fluid yellow large ui button" type="submit">Login</button>
</form>
Please check what custom-submit directive are doing. Please give me answers the based on that. I know I can check the form valid status on controller level, but why this way I can say only form is not valid, I can not say which field is empty (we can also check this which field is valid, but don't know how to enable the error divs from controllers)
Please refer this...
https://gist.github.com/maikeldaloo/5133963
Thanks,
Just set a state and show/hide the errors depending on the state:
onSubmit() {
if(hasErrors()) {
this.hasErrors = true;
return false; // preventDefault
}
this.postData(); // process submit event
}
<div *ngIf="hasError">
... error info here
</div>
This way we actually validate whether you have entered the correct values or not. If any of the value fails then submit button gets disabled otherwise enabled.
For ex: E-mail : If email id doesn't have # and ., then it will be considered as dirty, which wouldn't lead to enable the submit button.
Edited:
To display the message you can do one thing:
<input type="submit" ng-click="done(heroForm.form.valid)" />
And in controller you can do this way.
$scope.done = function(valid){
if(valid) {
// Form content is valid, process it
} else {
// show error and do nothing.
}
}