How do i debounce form in angular2 - javascript

I went through lots of post, but did not find what I was looking for.
Basically,
I am showing user validation on form changes. My template looks like this:
<div class="form-group"
[class.error]="!loginForm.find('email').valid && loginForm.find('email').touched">
<div class="input-wrapper">
<input type ="email"
class="form-control"
id="email-input"
placeholder="Email"
formControlName="email">
</div>
<div *ngIf="loginForm.controls['email'].dirty && !loginForm.controls['email'].valid"
class="alert-msg">Email is invalid</div>
</div>
And, looking at other posts, my TS which debounces form is this:
this.loginForm.valueChanges.debounceTime(500).subscribe(form => {
console.log(form, this.loginForm);
});
Now, the console logs are actually debouncing. But, the validation message does not debounce. It shows up straight away the message.
Is there a way to overcome this issue?
Thanks, for stopping by,

I believe the debounceTime will only affect the code you have in the response form => { ... }.
So what you could do is set the validation there:
private loginFormIsValid:boolean;
private emailIsNotValid:boolean;
ngOnInit() {
this.loginForm.valueChanges.debounceTime(500).subscribe(form => {
this.loginFormIsValid = !loginForm.find('email').valid
&& loginForm.find('email').touched;
this.emailIsNotValid = loginForm.controls['email'].dirty
&& !loginForm.controls['email'].valid;
console.log(form, this.loginForm);
});
}
...And then you would use it in you template as follows:
<div class="form-group" [class.error]="!loginFormIsValid">
<div class="input-wrapper">
<input type ="email"
class="form-control"
id="email-input"
placeholder="Email"
formControlName="email">
</div>
<div *ngIf="emailIsNotValid"
class="alert-msg">Email is invalid</div>
</div>
You can take a look at a post on debouncing, it's a good example.

Related

jQuery validate single input in similar forms

I have two forms on a page that are identical, but I'm trying to validate the one field (which is email in this case), but I can't seem to get it to just validate the one input field as it just shows the error for both forms.
HTML:
<div class="general-form">
<div class="email-error" style="display:none;">
<p>You need valid email</p>
</div>
<div class="form-wrap">
<div class="form-row">
<input id="from-email" type="email" name="email" placeholder="Your Email" />
</div>
<div class="btn-row">
<button class="submit-btn">Submit</button>
</div>
</div>
</div>
<div class="general-form">
<div class="email-error" style="display:none;">
<p>You need valid email</p>
</div>
<div class="form-wrap">
<div class="form-row">
<input id="from-email" type="email" name="email" placeholder="Your Email" />
</div>
<div class="btn-row">
<button class="submit-btn">Submit</button>
</div>
</div>
</div>
JS:
$(".submit-btn").on("click", function() {
var $this = $(this);
var valid_email = $this.find("#from-email").val();
if (/(.+)#(.+){2,}\.(.+){2,}/.test(valid_email)) {
return true;
} else {
$this.parents().find(".email-error").show();
return false;
}
});
Overall, I can get it to pass through the validation, but the error message shows for both forms and I'm not sure how to get it so it only shows the error message for that particular form. I'm guessing that I'm pushing too far up the chain and it's testing for both of the forms, but I can't remember which one to target specifically if that makes any sense.
You doubled the id from-email that’s why. In your JS you are checking all fields with the id from-email in this case both of the inputs are checked because both the id.
If one of them is wrong you are searching for the email-error in all of your parents which will go up to the body and then find all off the error wrappers. $this.parents(“.general-form“) will do the deal and only go up to the wrapper of the input and error in your case.
Always make sure your id’s are unique.
Just add required> attribute and add this js
$("#formid").validate();

Unable to assign form control to template variable in Reactive Forms - angular?

I am new to angular let say, i have reactive form like follow
ngOnInit() {
this.registerFormGroup = this.formBuilder.group({
email: [ '', Validators.compose([Validators.required, Validators.email])],
password: this.formBuilder.group({
first: [ '', Validators.required ],
second: [ '', Validators.required, ]
})
});
}
and my angular template looks like follow
<div class="container">
<form [formGroup]="registerFormGroup"
(ngFormSubmit)="registerUser(registerFormGroup.value)" novalidate>
<div class="form-group" >
<label for="email">Email</label>
<input type="email" formControlName="email" placeholder="Enter Email"
class="form-control">
</div>
<div *ngIf="!registerFormGroup.get('password').get('first').valid"
class="alert alert-danger">
</div>
<div class="form-group text-center">
<button type="submit" class="btn btn-success btn-lg"
[disabled]="!registerFormGroup.valid">Submit</button>
</div>
For example, email field has two validations such as required and email type validate so depends upon the error I have to display error message so in my template am using like
<div *ngIf="!registerFormGroup.get('email').valid && (registerFormGroup.get('email').touched)"
class="alert alert-danger">
</div>
Instead of adding same registerFormGroup.get('email') again and again i trying to create template expression like #emailForm="registerFormGroup.get('email')" in
<input type="email" formControlName="email" placeholder="Enter Email" class="form-control" #emailForm="registerFormGroup.get('email')">
so that i can use use like
<div *ngIf="!emailForm.valid" class="alert alert-danger">
</div>
but i am getting error like
compiler.es5.js:1690 Uncaught Error: Template parse errors:
There is no directive with "exportAs" set to "registerFormGroup.get('email')" ("l>
]#emailForm="registerFormGroup.get('email')">
what mistake i made??
You can create common function to access form like below:
validateFormControl(controName: string) {
let control = registerFormGroup.get(controName);
return control.invalid && control.touched;
}
In Templete use this call wherever you need, you just need to pass your control name in function, you can modify this function as per your need as well and you do not need to use form.get all the time. This makes your template more cleaner and performance efficient.
<div *ngIf="validateFormControl('email')"
class="alert alert-danger">
error message
</div>
<div *ngIf="validateFormControl('password')"
class="alert alert-danger">
error message
</div>
Create a method on the component that returns if the form is valid or not and return it in the component
checkError(){ // either you can pass the form from the template or use the component for decleration
return registerFormGroup.get('email').valid;
}
In the template call
<div *ngIf="checkError()" class="alert alert-danger">
// Always make sure not to use controls in the template it will result in AOT compilation error
</div>
try this :
component.html
<div class="container">
<form [formGroup]="registerFormGroup"
(ngFormSubmit)="registerUser(registerFormGroup.value)" novalidate>
<div class="form-group" [ngClass]="{'has-error':!registerFormGroup.controls['email'].valid}">
<label for="email">Email</label>
<input type="email" formControlName="email" placeholder="Enter Email"
class="form-control">
<p class="alert alert-danger" *ngIf="registerFormGroup.controls['email'].dirty && !registerFormGroup.controls['email'].valid">Invalid email address</p>
</div>
<div class="form-group text-center">
<button type="submit" class="btn btn-primary" [disabled]="!registerFormGroup.valid">Submit</button>
</div>
</form>
</div>
component.ts
import { FormGroup, FormBuilder, Validators } from '#angular/forms';
export class AppComponent implements OnInit {
registerFormGroup: any;
constructor(
private formBuilder: FormBuilder
) {}
ngOnInit() {
this.registerFormGroup = this.formBuilder.group({
email: [null , Validators.compose([Validators.required, Validators.email])]
});
}
}
Angular team strongly discourage from using functions outputs in templates due to change detection strategy. You might be interested in following solution, using ngForm directive:
<div class="container">
<form [formGroup]="registerFormGroup"
(ngFormSubmit)="registerUser(registerFormGroup.value)" novalidate>
<div class="form-group" >
<label for="email">Email</label>
<input type="email" formControlName="email" placeholder="Enter Email "
class="form-control" #email="ngForm">
</div>
<div *ngIf="email.invalid"
class="alert alert-danger">
</div>
It's still a hush to copy-paste it in template, but at least you might have direct reference to control via it's template variable. I personally go with controller getter function still, but I'm posting this answer for sake of answer completeness.
Although I agree with the accepted answer (you should have a dedicated method in your form component that will encapsulate the validation process)
sometimes you need a quick check in the template:
The trick is to expose the formGroup from your component and use it like so:
Template:
<input id="name" class="form-control"
formControlName="name" required
[class.is-invalid]="
f.name.invalid &&
(f.name.touched ||
f.name.touched.dirty)">
Component:
//easily access your form fields
get f() { return this.checkoutForm.controls; }
I was also looking for a more elegant solution than calling form.get multiple times. Here is what I come up with using ngif
<div class="col-sm-6" *ngIf="form.get('sponsor') as sponsor">
<input type="text" formControlName="sponsor" id="sponsor" class="form-control" name="sponsor"
[class.is-invalid]="sponsor.errors && sponsor.touched">
</div>
using the as feature on ngIf to create a template variable

Field validation onBlur with Aurelia

I'm using Aurelia and Typescript to build a web page. I have a simple login form and I'd like to validate the user email and password.
I am using Aurelia validation and by default it validates the content of my input each time it changes, which can be annoying. (ex: getting an error message saying that the email is not valid when you're not even done typing it). So I'd like to do the validation onBlur instead (when the focus on the input is lost) and when the user clicks on the Login button.
Here's my code:
login.html
<template>
<section>
<div class="container col-lg-12">
<div class="col-md-4 col-md-offset-4 centered">
<h2 t="signin_sign_in"></h2>
<form role="form" submit.delegate="login()" validate.bind="validation">
<br if.bind="errors" />
<div if.bind="errors" repeat.for="error of errors" class="alert alert-danger">
<h4 repeat.for="message of error">${message}</h4>
</div>
<div class="form-group">
<label class="control-label" t="signin_email_address"></label>
<input type="text" class="form-control" value.bind="email">
</div>
<div class="form-group">
<label class="control-label" t="signin_password"></label>
<input type="password" class="form-control" value.bind="password">
</div>
<button type="submit" class="btn btn-primary" t="signin_sign_in"></button>
</form>
</div>
</div>
</section>
</template>
login.ts
#autoinject()
export class Login {
email: string;
password: string;
router: Router;
application: ApplicationState;
accountService: AccountService;
errors;
validation;
i18n: I18N;
constructor(router: Router, application: ApplicationState, accountService: AccountService, validation: Validation, i18n: I18N) {
this.router = router;
this.application = application;
this.accountService = accountService;
this.i18n = i18n;
this.errors = [];
this.validation = validation.on(this)
.ensure('email')
.isNotEmpty()
.isEmail()
.ensure('password')
.isNotEmpty()
.hasLengthBetween(8, 100);
}
navigateToHome(): void {
this.router.navigate("/welcome");
}
login(): void {
var __this = this;
this.validation.validate()
.then(() => this.accountService.signin(this.email, this.password, this.rememberMe)
.then(result => {
// Do stuff
})
.catch(error => {
// Handle error
}
}));
}
}
My first thought was to add
& updateTrigger:'blur':'paste'
to my binding in the HTML, but it doesn't work. The binding is updated correctly when focus is lost but the validation stops working. There's no error in the Chrome debug console either.
Any idea on how to do this? Is is possible at all?
There's different binding behaviours you can use to tell when the validation should trigger. You can read more about them in the Aurelia docs on validation.
From the docs;
The validate binding behavior obeys the associated controller's
validateTrigger (blur, change, changeOrBlur, manual). If you'd like to
use a different validateTrigger in a particular binding use one of the
following binding behaviors in place of & validate:
& validateOnBlur: the DOM blur event triggers validation.
& validateOnChange: data entry that changes the model triggers validation.
& validateOnChangeOrBlur: DOM blur or data entry triggers validation.
& validateManually: the binding is not validated
automatically when the associated element is blurred or changed by the
user.
I recently encountered this exact use case and I solved it using Aurelia's built in debounce feature.
<input type="text" class="form-control" id="email" placeholder="Email"
value.bind="email & validateOnChangeOrBlur & debounce:600 ">
600ms is an arbitrary value, but you can always play around with it as needed.

Using angular 1.3 ngMessage for form submission errors

I've gotten an example of form validation working correctly in my app for the login page, looking something like this:
<div class="form-group" >
<label for="password">Password</label>
<input type="password"
id="password"
name="password"
class="form-control"
placeholder="Create password"
ng-model="password"
required
minlength="{{passwordLength}}"
>
<div class="help-block text-danger"
ng-messages="form.password.$error"
ng-if="form.password.$touched || form.$submitted"
>
<div class="text-danger">
<div ng-message="required">A password is required</div>
<div ng-message="minlength" >Password must be at least {{passwordLength}} characters</div>
</div>
</div>
</div>
This works great for "required" and "minlength" checks, which can be done before submission. However after submission, we can get back a 401 for an invalid username/password. Angular 1.3 has an async validaiton concept, but it seems to run before submission, and it seems unreasonable to try to login twice (once just to see if they could and prompt an error)
Is there a reasonable way to use the ng-messages concept to display this post-submission error?
I figured it out. You can just manually validate/invalidate the form:
<div class="help-block text-danger">
<div class="text-danger"
ng-messages="form.password.$error"
ng-if="form.password.$touched || form.$submitted">
<div ng-message="required">Password is required</div>
<div ng-message="minlength">*Password must be at least {{passwordLength}} characters</div>
<div ng-message="correctPassword">Username/Password combination is incorrect</div>
</div>
</div>
and in your controller, on submit:
$scope.login = function(){
$scope.form.password.$setValidity("correctPassword", true);
// ...do some stuff...
$http.post('/someUrl', {msg:'hello word!'})
.success(function(){})
.error(function() {
$scope.form.password.$setValidity("correctPassword", false);
});
}

Validating Form with Javascript (Simple Test)

var name = document.getElementById('contact-name'),
email = document.getElementById('contact-email'),
phone = document.getElementById('contact-phone'),
message = document.getElementById('contact-message');
function checkForm() {
if (name.value == '') {
alert('test');
}
}
I was simply trying to make sure everything was working before I began learning actual client-side validation.
Here is the HTML
<form role='form' name='contactForm' action='#' method="POST" id='contact-form'>
<div class="form-group">
<label for="contact-name">First and Last Name</label>
<input type="text" class="form-control" id="contact-name" name="contactName" placeholder="Enter your name.." pattern="[A-Za-z]+\s[A-Za-z]+">
</div>
<div class="form-group">
<label for="contact-email">Email address</label>
<input type="email" class="form-control" id="contactEmail" name="contactEmail" placeholder="Enter Email" required>
</div>
<div class="form-group">
<label for="contact-phone">Phone Number</label>
<input type="number" class="form-control" id="contactPhone" name="contactPhone" placeholder="Enter Phone Number" required'>
</div>
<div class="form-group">
<label for='contactMessage'>Your Message</label>
<textarea class="form-control" rows="5" placeholder="Enter a brief message" name='contactMessage' id='contact-message' required></textarea>
</div>
<input type="submit" class="btn btn-default" value='Submit' onclick='checkForm()'>
</fieldset>
</form>
I took the required attribute off, and if I leave the name field empty it goes right to the other one when i click submit. To check whether javascript was working at all, i did an basic onclick function that worked.
Maybe someone can explain to me what is wrong with the checkForm function. Thanks in advance.
P.S The form-group and form-control classes belong to bootstrap
Change your javascript to this:
var contactName = document.getElementById('contact-name'),
email = document.getElementById('contact-email'),
phone = document.getElementById('contact-phone'),
message = document.getElementById('contact-message');
function checkForm() {
if (contactName.value === '') {
alert('test');
}
}
Okay, Hobbes, thank you for editing your question, now I can understand your problem.
Your code faces three two issues.
Your control flow. If you want to validate your field, you have to obtain its value upon validation. You instead populate variable name when the page loads, but the user will enter the text only after that. Hence you need to add var someVariableName = document.getElementById(...); to the beginning of the checkForm() function.
global variables. Please do not use them like that, it is a good design to avoid global variables as much as possible, otherwise you bring upon yourself the danger of introducing side effects (or suffering their impact, which happens in your situation). The global context window already contains a variable name and you cannot override that. See window.name in your console. You can of course use var name = ... inside the function or a block.
Even if you fix the above, you will still submit the form. You can prevent the form submission if you end your checkForm() function with return false;
For clarity I append the partial javascript that should work for you:
function checkForm() {
var name = document.getElementById('contact-name');
if (name.value == '') {
alert('test');
return false;
}
}
EDIT: As Eman Z pointed out, the part 1 of the problem does not really prevent the code from working as there's being retrieved an address of an object (thanks, Eman Z!),

Categories

Resources