override default angularjs error messages - "Required" "Invalid" - javascript

I have a input field, where i have to show error messages, but its not working.. the error messages are not shown.
<div class="form-group grouped">
<div>
<label for="card-routingNumber">Number:</label>
<input name="cr" ng-model="card.rn" type="number" pattern="[0-9]*" id="card-rn" class="form-control" validate-on="submit" required />
<span class="help-block" ng-show"form.cr.$error.required">Field is empty</span>
</div>
</div>
When i click on submit, i need to show an error message if the input is empty.. but when i try... it always says "Required"

Add "novalidate" attribute to your form.

You can try
<span class="help-block" ng-show=**"!myForm.myInput.$valid"**>Field is empty</span>

remove required attribute from the <input>
<input name="cr" ng-model="card.rn" type="number" pattern="[0-9]*" id="card-rn" class="form-control" validate-on="submit" />

Related

maxlegth not working using template driven form in angular 6

I am developing one register form in that form i need maxlength validation but using template driven form can't show maxlength alert message.
<input type="text" class="form-control" placeholder="Enter Name"maxlength="4"
name="name" [(ngModel)]="name" ngModel required #username="ngModel">
<div *ngIf="username.invalid && (username.dirty || username.touched)">
<p style="color:red;font-size:10px;" *ngIf='username.invalid.maxlength'>
You enter only 4 characters.
</p>
</div>
Try:
<form name="form" role="form" #form="ngForm">
<div class="form-group">
<label class="form-control-label" for="userName">UserName</label>
<input
type="userName"
class="form-control"
id="userName"
name="userName"
#userNameInput="ngModel" //ngModel variable and template variable should not be the same
[(ngModel)]="userName"
minlength=4
maxlength=50
required>
<div *ngIf="userNameInput.dirty && userNameInput.invalid">
<small class="form-text text-danger" *ngIf="userNameInput.errors.required">
Your userName is required.
</small>
<small class="form-text text-danger" *ngIf="userNameInput.errors.minlength">
Your userName is required to be at least 4 characters.
</small>
<small class="form-text text-danger" *ngIf="userNameInput.errors.maxlength">
Your username cannot be longer than 50 characters.
</small>
</div>
</div>
</form>
DEMO
For me, the issue was input type="number".
Once I removed the type number maxLength worked.
Angular version: 8
username.invalid will be username.errors?
*ngIf="username.errors?.maxlength"
so there are a couple of steps to follow to validate your input like
please check this
<input
type="text"
placeholder="Your full name"
name="name"
ngModel
#userName="ngModel"
maxlength="4"
required>
<div *ngIf="userName.errors?.minlength && userName.touched" class="error">
Minimum of 4 characters
</div>
?.prop is called the “Safe navigation operator”
that means it avoids an exception for null and undefined values in in property paths
As if you use maxlength property for input type it does not allows a user to type anything beyond that length [As I tested in Chrome].
So if you want to display an alert or error message then you can check for input's length property and display error message:
HTML:
Remove maxlength from input type and check for username.value?.length in if condition
<input type="text" class="form-control" placeholder="Enter Name" name="username" [(ngModel)]="name" ngModel required #username="ngModel">
<div *ngIf="username.value?.length > 4">
<p style="color:red;font-size:10px;">
You enter only 4 characters.
</p>
</div>
WORKING DEMO
I needed to validate the length using the template only and I need it to invalidate the form as well so here is what I did using pattern
<textarea class="form-control" id="Command" rows="3" name="dialogCommand" pattern="^(.|\n){0,4000}$" #comment="ngModel" [(ngModel)]="comment" [ngClass]="{ 'is-invalid': comment?.errors?.pattern }"></textarea>
<div class="text-danger small" *ngIf="comment?.errors?.pattern">The comment cannot be greater than 4000 characters long</div>
This will count on multiple lines.
Hope this helps someone

Angular template driven form on submit validation

In angular js, we have $submitted to populate error messages on submit click.
How can we display all validation errors on submit click in Angular
HTML:
<form #nameForm="ngForm" novalidate (ngSubmit)="saveNameForm(formModel)">
<div class="form-group">
<label for="inputName" class="form-control-label"> Name</label>
<input type="text" id="inputName" name="lotCode [(ngModel)]="formModel.name" #lotCode="ngModel" aria-describedby="nameHelp"
autocomplete="new-password" required>
<small id="nameHelp" class="text-danger" *ngIf="lotCode.invalid && lotCode.touched">Required</small>
</div>
<div class="form-group">
<label for="inputDescription" class="form-control-label"> Description</label>
<input type="text" id="inputDescription" name="desCode" [(ngModel)]="formModel.description" #desCode="ngModel" aria-describedby="descriptionHelp"
autocomplete="new-password" required>
<small id="descriptionHelp" class="text-danger" *ngIf="desCode.invalid && desCode.touched">Required</small>
</div>
<button type="submit">Submit </button>
</form>
Component:
export class AppComponent {
formModel: FormModel= new FormModel();
saveNameForm(formModel){
console.log(formModel)
}
}
export class FormModel {
name: string;
description:string;
}
https://stackblitz.com/edit/angular-rizsuy?file=src%2Fapp%2Fapp.component.ts
Here is the solution:
https://stackblitz.com/edit/angular-8jaaqz?file=src%2Fapp%2Fapp.component.html
You should use a variable to set submitted
if submitted then will display error
Angular uses the same form validation that native HTML5 does. Just do this in an Angular context. In the following example, we can use *ngIf to control the display of the messages, and .dirty and .touched to determine if the user interacted with the input.
Example from docs:
<input id="name" name="name" class="form-control"
required minlength="4" appForbiddenName="bob"
[(ngModel)]="hero.name" #name="ngModel" >
<div *ngIf="name.invalid && (name.dirty || name.touched)"
class="alert alert-danger">
<div *ngIf="name.errors.required">
Name is required.
</div>
<div *ngIf="name.errors.minlength">
Name must be at least 4 characters long.
</div>
<div *ngIf="name.errors.forbiddenName">
Name cannot be Bob.
</div>
</div>

show error when mouseleave input

In Angular4 how do I show error input text (for example input is required when mouseleave input ... when mouseleave input text error is showing and not when I am in input I show error).
My code:
<input type="email" class="form-control" name="email" placeholder="Enter email" [(ngModel)]="data.email" #dataemail="ngModel" required minlength="12" pattern="^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$" >
<div *ngIf="dataemail.errors?.pattern" class="alert alert-danger">Email is invalid</div>
Error showing in div.class="alert alert-danger" when I try to type text in input email but how do I show error when mouseleave input email.
You need to set the updateOn option to 'blur'. It will trigger the validation only after the user blurs the input.
<input
[(ngModel)]="data.email"
[ngModelOptions]="{ updateOn: 'blur' }" <!-- add this -->
type="email"
class="form-control"
name="email"
placeholder="Enter email"
#dataemail="ngModel"
required
minlength="12"
pattern="^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$">
</div>
<div *ngIf="dataemail.errors?.pattern" class="alert alert-danger">
Email is invalid
</div>
Live demo

Confirm password custom directive is not working in Angular

I try to implement confirm password validation in angular view. write new
directive in app.js
and add compare-to in confirm password text box
<div class="form-group">
<label class="control-label col-sm-2" for="pwd">Password:</label>
<div class="col-sm-10">
<input type="password"
class="form-control"
placeholder="Enter password"
ng-model="Password"
ng-minlength="5">
<span class="validationMessage" ng-show="frm.password.$dirty && frm.password.$error.required">Required!</span>
<span class="validationMessage" ng-show="frm.password.$dirty && frm.password.$error.minlength">Min length 5!</span>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="pwd">Confirm Password:</label>
<div class="col-sm-10">
<input type="password"
class="form-control"
ng-model="ConfirmPassword"
required
compare-to="Password"
placeholder="Enter Confirm password">
<span class="validationMessage" ng-show="frm.ConfirmPassword.$error">Required!</span>
</div>
</div>
But the confirm password is not shows any validation. and show a error message Cannot set property 'compareTo' of undefined in chrome.
It's working, mostly. You just have little logic flaws there.
First of all, using <label for="x"> expects template to have a element with id="x" present. Nothing major there but when you check for form validity you should refer to your form fields, not underlying model.
So instead of frm.<ng-model-var>.$error you should type in frm.<form-field-name>.$error.
You need to add names for your inputs, and check your form validation logic once more. This should work fine for your password.
<!-- added required, input name, changed validation logic -->
<input type="password"
name="password"
class="form-control"
placeholder="Enter password"
ng-model="Password"
required
ng-minlength="5" />
<span class="validationMessage"
ng-show="frm.password.$error.required">
Required!
</span>
<span class="validationMessage"
ng-show="frm.password.$dirty && frm.password.$error.minlength">
Min length 5!
</span>
and this for your confirm password.
<!-- added input name, changed validation logic -->
<input type="password"
name="confirmpassword"
class="form-control"
placeholder="Enter Confirm password"
ng-model="ConfirmPassword"
required
compare-to="Password" />
<span class="validationMessage"
ng-show="frm.password.$valid && frm.confirmpassword.$invalid">
Passwords do not match!
</span>
Try with updated versions
http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js
https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.2/angular-route.min.js
and in your controller.js add this..
'ngRoute'
var loginApp = angular.module('indexApp', ['authModule','requestModule','ngRoute']);

Form submits even with validation errors

The form submits even when there are validation errors. How do I disable the submit button when there are validation errors? Here is the .js file
,submitFu:function(){
_.validateFu(_.labels)
if(!_.form.has('.'+_.invalidCl).length)
$.ajax({
type: "POST",
url:_.mailHandlerURL,
data:{
name:_.getValFromLabel($('.name',_.form)),
email:_.getValFromLabel($('.email',_.form)),
phone:_.getValFromLabel($('.phone',_.form)),
//fax:_.getValFromLabel($('.fax',_.form)),
//state:_.getValFromLabel($('.state',_.form)),
message:_.getValFromLabel($('.message',_.form)),
owner_email:_.ownerEmail,
stripHTML:_.stripHTML
},
success: function(){
_.showFu()
}
})
},
showFu:function(){
_.success.slideDown(function(){
setTimeout(function(){
_.success.slideUp()
_.form.trigger('reset')
},_.successShow)
})
},
And here is the form:
<form id="contact-form" action="contactTq.php" method="post">
<div class="success"> Contact form submitted! <strong>We will be in touch soon.</strong></div>
<fieldset>
<label class="name">
<input type="text" name="name" value="Enter Your Name:" >
<span class="error">*This is not a valid name.</span>
<span class="empty">*This field is required.</span>
<span class="clear"></span>
</label>
<label class="email">
<input type="text" name="email" value="Enter Your E-mail:">
<span class="error">*This is not a valid email address.</span>
<span class="empty">*This field is required.</span>
<span class="clear"></span>
</label>
<label class="phone">
<input type="text" name="phone" value="Enter Your Phone (optional):">
<span class="error">*This is not a valid phone number.</span>
<span class="clear"></span>
</label>
<label class="message">
<textarea name="msg">Enter Your Message:</textarea>
<span class="error">*The message is too short.</span>
<span class="empty">*This field is required.</span>
<span class="clear"></span>
</label>
<div class="buttons"><strong><a class="button" data-type="reset">Reset<span></span></a></strong><strong><a class="button" data-type="submit" href="javascript:{}" onclick="document.getElementById('contact-form').submit();">Submit<span></span></a></strong></div>
</fieldset>
</form>
Knockout.js does a wonderful job of doing exactly what you're looking for. You can slip your existing javascript into a ViewModel, and then put a data-bind on your button to enable if all fields validate. You can see how to do so here: http://knockoutjs.com/documentation/enable-binding.html
It appears that you are submitting the form as soon as the button is clicked because the onclick handler is written as below:
onclick="document.getElementById('contact-form').submit();"
Just change the onclick handler to execute the submitFu function and that should do the trick.
Change the onclick event of your submit button to
onclick="return submitFu()"
If the validation fails, return false and the form will not submit. I think you can do the same with the onsubmit event of the form.

Categories