I have a simple form that needs to validate if the beginning and the end of the input is not space.
In HTML5, I will do this:
<input type="text" pattern="^(?!\s|.*\s$).*$">
What is the right property for validation pattern in the new Angular 2 ngControl directive? The official Beta API is still lacking documentation on this issue.
Now, you don't need to use FormBuilder and all this complicated valiation angular stuff. I put more details from this (Angular 2.0.8 - 3march2016):
https://github.com/angular/angular/commit/38cb526
Example from repo :
<input [ngControl]="fullName" pattern="[a-zA-Z ]*">
I test it and it works :) - here is my code:
<form (ngSubmit)="onSubmit(room)" #roomForm='ngForm' >
...
<input
id='room-capacity'
type="text"
class="form-control"
[(ngModel)]='room.capacity'
ngControl="capacity"
required
pattern="[0-9]+"
#capacity='ngForm'>
Alternative approach (UPDATE June 2017)
Validation is ONLY on server side. If something is wrong then server return error code e.g HTTP 400 and following json object in response body (as example):
this.err = {
"capacity" : "too_small"
"filed_name" : "error_name",
"field2_name" : "other_error_name",
...
}
In html template I use separate tag (div/span/small etc.)
<input [(ngModel)]='room.capacity' ...>
<small *ngIf="err.capacity" ...>{{ translate(err.capacity) }}</small>
If in 'capacity' is error then tag with msg translation will be visible. This approach have following advantages:
it is very simple
avoid backend validation code duplication on frontend (for regexp validation this can either prevent or complicate ReDoS attacks)
control on way the error is shown (e.g. <small> tag)
backend return error_name which is easy to translate to proper language in frontend
Of course sometimes I make exception if validation is needed on frontend side (e.g. retypePassword field on registration is never send to server).
Since version 2.0.0-beta.8 (2016-03-02), Angular now includes a Validators.pattern regex validator.
See the CHANGELOG
You could build your form using FormBuilder as it let you more flexible way to configure form.
export class MyComp {
form: ControlGroup;
constructor(#Inject()fb: FormBuilder) {
this.form = fb.group({
foo: ['', MyValidators.regex(/^(?!\s|.*\s$).*$/)]
});
}
Then in your template :
<input type="text" ngControl="foo" />
<div *ngIf="!form.foo.valid">Please correct foo entry !</div>
You can also customize ng-invalid CSS class.
As there is actually no validators for regex, you have to write your own. It is a simple function that takes a control in input, and return null if valid or a StringMap if invalid.
export class MyValidators {
static regex(pattern: string): Function {
return (control: Control): {[key: string]: any} => {
return control.value.match(pattern) ? null : {pattern: true};
};
}
}
Hope that it help you.
custom validation step by step
Html template
<form [ngFormModel]="demoForm">
<input
name="NotAllowSpecialCharacters"
type="text"
#demo="ngForm"
[ngFormControl] ="demoForm.controls['spec']"
>
<div class='error' *ngIf="demo.control.touched">
<div *ngIf="demo.control.hasError('required')"> field is required.</div>
<div *ngIf="demo.control.hasError('invalidChar')">Special Characters are not Allowed</div>
</div>
</form>
Component App.ts
import {Control, ControlGroup, FormBuilder, Validators, NgForm, NgClass} from 'angular2/common';
import {CustomValidator} from '../../yourServices/validatorService';
under class
define
demoForm: ControlGroup;
constructor( #Inject(FormBuilder) private Fb: FormBuilder ) {
this.demoForm = Fb.group({
spec: new Control('', Validators.compose([Validators.required, CustomValidator.specialCharValidator])),
})
}
under {../../yourServices/validatorService.ts}
export class CustomValidator {
static specialCharValidator(control: Control): { [key: string]: any } {
if (control.value) {
if (!control.value.match(/[-!$%^&*()_+|~=`{}\[\]:";##'<>?,.\/]/)) {
return null;
}
else {
return { 'invalidChar': true };
}
}
}
}
My solution with Angular 4.0.1: Just showing the UI for required CVC input - where the CVC must be exactly 3 digits:
<form #paymentCardForm="ngForm">
...
<md-input-container align="start">
<input #cvc2="ngModel" mdInput type="text" id="cvc2" name="cvc2" minlength="3" maxlength="3" placeholder="CVC" [(ngModel)]="paymentCard.cvc2" [disabled]="isBusy" pattern="\d{3}" required />
<md-hint *ngIf="cvc2.errors && (cvc2.touched || submitted)" class="validation-result">
<span [hidden]="!cvc2.errors.required && cvc2.dirty">
CVC is required.
</span>
<span [hidden]="!cvc2.errors.minlength && !cvc2.errors.maxlength && !cvc2.errors.pattern">
CVC must be 3 numbers.
</span>
</md-hint>
</md-input-container>
...
<button type="submit" md-raised-button color="primary" (click)="confirm($event, paymentCardForm.value)" [disabled]="isBusy || !paymentCardForm.valid">Confirm</button>
</form>
Without make validation patterns, You can easily trim begin and end spaces using these modules.Try this.
https://www.npmjs.com/package/ngx-trim-directive
https://www.npmjs.com/package/ng2-trim-directive
Thank you.
Related
I have a list of inputs using ngFor + input I am displaying it as below
<div*ngFor="let esControl of extraServicesControls.controls; let i = index; last as isLast; first as isFirst" [formGroup]="esControl">
<input
type="number"
name=""
id=""
class="form-control form-control-sm"
aria-label="Enter insured amount"
[value]="
esControl.value.specialService?.inputParameters &&
(esControl.value.specialService?.inputParameters)[0]?.value
"
(keyup)="valuechangeInput($event.target.value, esControl.value.specialService)"
/>
</div>
How to call API on each input in list with debounce time of 1000 ms when type letter any input
For this issue I am suggesting to use angular reactive forms.
In order to user Angular reactive forms
Import reactive forms module to your module
import { ReactiveFormsModule } from '#angular/forms';
#NgModule({
imports: [
// other imports ...
ReactiveFormsModule
],
})
export class AppModule { }
In the ts file create a new formGroup
import { debounceTime} from 'rxjs/operators';
import { FormBuilder } from '#angular/forms';
constructor(private fb:FormBuilder){
this.form= this.fb.group({
insertAmount: ''
});
//Then subscribe for valuechange
this.form.valueChanges.pipe(debounceTime(500)).subscribe((val)=>{
there is a new value for the input. Check logic here
})
}
In this code the 500 means the amount of ms the stream has to wait before emitting a new value. In the mean time all the new value will be discarded.
More detail about reactive forms:https://angular.io/guide/reactive-forms
More detail about RXJS debounceTime operator https://www.learnrxjs.io/learn-rxjs/operators/filtering/debouncetime
The reactive form is a pretty good kind of approach to achieve such debounceTime functionality.
The simpler approach is similar to what you did
html
<input
type="number"
name=""
id=""
class="form-control form-control-sm"
aria-label="Enter insured amount"
[value]="
esControl.value.specialService?.inputParameters &&
(esControl.value.specialService?.inputParameters)[0]?.value
"
(keyup)="valuechangeInput($event.target.value,i)"
/>
</div>
.ts
import {Replaysubject} from "rxjs"
private inputValue: Replaysubject<string[]>= new Replaysubject()
constructor(private fb:FormBuilder){
this.inputValue.pipe(debounceTime(500)).subscribe((val)=>{
there is a new value for the input. Check logic here
})
}
valuechangeInput(value:string,index:number){
this.inputValue.next({value,index});
}
How would you read the input value ?
On the reacjs site I see very complicated way !!
https://reactjs.org/docs/forms.html
I just want to read the value and submit it via ajax fetch() request. I.e. I don't need to manage bindings, events and such ...
The easiest way by far to read values from html controls is by using an event handler.
export default class myComponent extends Component {
person = {};
onChange = field => e => {
this.person[field] = e.target.value;
};
render() {
return (
<Input
id="firstName"
name="firstName"
autoComplete="firstName"
autoFocus
onChange={this.onChange('FirstName')}
/>
);
}
}
In the above code snippet we are basically telling react to fire the onChange member on an update of firstName control update. Our method will receive an event e, that has a handle to our control and we can basically probe it's value member to get what's typed in (much like jquery's $('#element').value()).
Why is it the easiest method? because it's generic enough to allow you to handle multiple inputs in a react component. Notice that, I'm also instructing React to pass me the control name in addition to the event, and using this method I can basically know exactly which of my inputs (in case of multiple) caused the event to fire.
Reading user input value is feasible and recommended via event handlers.
Below example would explain how to read input value and send it to the backend via fetch when Form is submitted
class Test extends Component{
constructor(props){
super(props);
this.state = {
name: “”
}
}
handleChange = event => {
this.setState({name: event.target.value});
}
handleSubmit = () => {
//send the value via fetch backend I.e., this.state.name
}
render(){
const { name } = this.state;
render(
<form onSubmit={this.handleSubmit}
<label>
Name:
<input type="text" value={name} onChange={this.handleChange} name="name" />
</label>
<input type="submit" value="Submit" />
</form>
)
}
}
I am building a component (html, css, spec.ts, ts) in angular in which I always want endDate > startDate. I have followed this link https://material.angular.io/components/datepicker/overview in order make multiple datepickers.
This is the html which I have used for startDate and endDate.
startDate:
<div class="item item-1" fxFlex="50%" fxFlexOrder="1">
<mat-form-field>
<input matInput [matDatepicker]="picker1" placeholder="{{'PORTAL.STARTDATE' | translate}}" type="text" formControlName="startDate" [(ngModel)]="unavailability.startDate" [readonly]="!componentPermission.writePermission">
<mat-datepicker-toggle matSuffix [for]="picker1"></mat-datepicker-toggle>
<mat-datepicker #picker1></mat-datepicker>
</mat-form-field>
</div>
endDate:
<div class="item item-2" fxFlex="50%" fxFlexOrder="2">
<mat-form-field>
<input matInput [matDatepicker]="picker2" placeholder="{{'PORTAL.ENDDATE' | translate}}" type="text" formControlName="endDate" [(ngModel)]="unavailability.endDate" [readonly]="!componentPermission.writePermission">
<mat-datepicker-toggle matSuffix [for]="picker2"></mat-datepicker-toggle>
<mat-datepicker #picker2></mat-datepicker>
</mat-form-field>
</div>
The validateForm() code which I have used in the ts is:
validateForm() {
this.unavailabilityForm = this.formBuilder.group({
'startDate': [''],
'endDate': ['']
});
}
I am pretty sure I have to make some changes in the validateForm() code but I am not sure what changes I have to make.
Since you seem to be going with a mix of reactive form and template driven, I would choose a reactive form completely. Implementing Validation is also in my opinion easier and cleaner. This also then means, you can drop ngModel altogether, which I would then strongly suggest, since it can cause unexpected issues to have two bindings (form control and ngModel). EDIT 2/2019: ngModel together with reactive forms are now also luckily not allowed since v7. That is in my opinion good, since it was misused way too much!
So build your form and attach a custom validator. In case you have a large form, I would attach the custom validator to a nested group of your dates, as it sits in this example, the validator is firing whenever there is any change in the form, doesn't matter if it's the date fields, or some other field.
constructor(private formBuilder: FormBuilder) {
this.unavailabilityForm = this.formBuilder.group({
startDate: [''],
endDate: ['']
}, {validator: this.checkDates});
}
If you are getting your values for variable unavailability at a later stage, you can use patchValue or setValue to assign the values to your form controls:
this.unavailabilityForm.setValue({
startDate: this.unavailability.startDate;
endDate: this.unavailability.endDate;
})
The custom validator simply checks that the end date is a later date than the startdate and returns null if it is valid, or then a custom validation error:
checkDates(group: FormGroup) {
if(group.controls.endDate.value < group.controls.startDate.value) {
return { notValid:true }
}
return null;
}
and then you can display this custom error in template with:
<small *ngIf="unavailabilityForm.hasError('notValid')">Not valid</small>
Also remember to mark this formgroup in your form tag:
<form [formGroup]="unavailabilityForm">
I was playing around with aurelia-validatejs and was able to validate simple fields on a page. On the same page, I tried initializing a object and bind validation to that object and it stops working:
user_data:IUserData = {
Login:"",
Id : null,
UserProfile: {
UserId: null
},
Permissions: null
};
constructor(){
this.reporter = ValidationEngine.getValidationReporter(this.user_data);
// if I just use this and not user_data object,
// it works and error message is displayed in UI
this.validator = new Validator(this.user_data)
// when I use this.user_data (user_data object), it does validate
// and I can see validation result on console, but it's not shown in UI
.ensure('Login').required().length({minimum: 3, maximum:10});
this.observer = this.reporter.subscribe(result => {
console.info(result);
});
}
Someone mentioned that validatejs looks for a label, and I do have it, it worked when I initialize on this object but as soon as I want to validate on this.user_data property, it just doesn't display in UI, but I can see it on console.
<form action="" submit.delegate="createUser()">
<div class="input-group ${user_data.Login | loginClass}">
<label></label>
<input placeholder="Login" type="text" class="form-control"
keyup.delegate="validate()" value.bind="user_data.Login & validate">
</div>
</form>
this doesn't work, but if I clear user_data like:
user_data:IUserData = {
Login:"",
Id : null,
UserProfile: {
UserId: null
},
Permissions: null
};
constructor(){
this.reporter = ValidationEngine.getValidationReporter(this);
//if I just use this and not user_data object,
//it works and error message is displayed in UI
this.validator = new Validator(this)
.ensure('Login').required().length({minimum: 3, maximum:10});
this.observer = this.reporter.subscribe(result => {
console.info(result);
});
}
and
<form action="" submit.delegate="createUser()">
<div class="input-group ${user_data.Login | loginClass}">
<label></label>
<input placeholder="Login" type="text" class="form-control"
keyup.delegate="validate()" value.bind="Login & validate">
</div>
</form>
This works and is displayed in UI. I searched a little bit on stackoverflow and got few results similar (My problem is similar. I have error messages on UI if I don't use it on a object but when I try to use it on an object, it logs on console but it doesn't display in UI)
I also found this but it wasn't of much help.
I found one more which wasn't of much help either.
I understand there are a lot of articles which might make this question marked duplicate, the reason I'm asking is aurelia is quite new technology and stuffs are changing quite frequently.
Thanks in advanced!
So I dug around a little bit and asked developers in Gitter. As it turns out, it's a bug in validatejs plugin.
Recent changes were made to make something available on all classes, and when that change was done, validatejs looks for validationError Reporter on same model even if we provide different model.
A small hacky workaround is to have
this.__validationReporter__ = ValidationEngine
.getValidationReporter(this.user_data);
Instead of:
this.reporter = ValidationEngine.getValidationReporter(this.user_data);
I have reported this issue and will update once they come up with something.
For now I'm gonna use
this.__validationReporter__ = ValidationEngine
.getValidationReporter(this.user_data);
Or one other workaround is to downgrade to 0.3.x which is not very recommended as there might have been some important changes.
Have you used form-group? Usually our validation problems come down to HTML structure not conforming to the library.
<form action="" submit.delegate="createUser()">
<div class="form-group ${user_data.Login | loginClass}">
<label></label>
<input placeholder="Login" type="text" class="form-control"
keyup.delegate="validate()" value.bind="Login & validate">
</div>
</form>
I have an angular app that contains a save button taken from the examples:
<button ng-click="save" ng-disabled="form.$invalid">SAVE</button>
This works great for client side validation because form.$invalid becomes false as user fixes problems, but I have an email field which is set invalid if another user is registered with same email.
As soon as I set my email field invalid, I cannot submit the form, and the user has no way to fix that validation error. So now I can no longer use form.$invalid to disable my submit button.
There must be a better way
This is another case where a custom directive is your friend. You'll want to create a directive and inject $http or $resource into it to make a call back to the server while you're validating.
Some pseudo code for the custom directive:
app.directive('uniqueEmail', function($http) {
var toId;
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, elem, attr, ctrl) {
//when the scope changes, check the email.
scope.$watch(attr.ngModel, function(value) {
// if there was a previous attempt, stop it.
if(toId) clearTimeout(toId);
// start a new attempt with a delay to keep it from
// getting too "chatty".
toId = setTimeout(function(){
// call to some API that returns { isValid: true } or { isValid: false }
$http.get('/Is/My/EmailValid?email=' + value).success(function(data) {
//set the validity of the field
ctrl.$setValidity('uniqueEmail', data.isValid);
});
}, 200);
})
}
}
});
And here's how you'd use it in the mark up:
<input type="email" ng-model="userEmail" name="userEmail" required unique-email/>
<span ng-show="myFormName.userEmail.$error.uniqueEmail">Email is not unique.</span>
EDIT: a small explanation of what's happening above.
When you update the value in the input, it updates the $scope.userEmail
The directive has a $watch on $scope.userEmail it set up in it's linking function.
When the $watch is triggered it makes a call to the server via $http ajax call, passing the email
The server would check the email address and return a simple response like '{ isValid: true }
that response is used to $setValidity of the control.
There is a in the markup with ng-show set to only show when the uniqueEmail validity state is false.
... to the user that means:
Type the email.
slight pause.
"Email is not unique" message displays "real time" if the email isn't unique.
EDIT2: This is also allow you to use form.$invalid to disable your submit button.
I needed this in a few projects so I created a directive. Finally took a moment to put it up on GitHub for anyone who wants a drop-in solution.
https://github.com/webadvanced/ng-remote-validate
Features:
Drop in solution for Ajax validation of any text or password input
Works with Angulars build in validation and cab be accessed at formName.inputName.$error.ngRemoteValidate
Throttles server requests (default 400ms) and can be set with ng-remote-throttle="550"
Allows HTTP method definition (default POST) with ng-remote-method="GET"
Example usage for a change password form that requires the user to enter their current password as well as the new password.:
<h3>Change password</h3>
<form name="changePasswordForm">
<label for="currentPassword">Current</label>
<input type="password"
name="currentPassword"
placeholder="Current password"
ng-model="password.current"
ng-remote-validate="/customer/validpassword"
required>
<span ng-show="changePasswordForm.currentPassword.$error.required && changePasswordForm.confirmPassword.$dirty">
Required
</span>
<span ng-show="changePasswordForm.currentPassword.$error.ngRemoteValidate">
Incorrect current password. Please enter your current account password.
</span>
<label for="newPassword">New</label>
<input type="password"
name="newPassword"
placeholder="New password"
ng-model="password.new"
required>
<label for="confirmPassword">Confirm</label>
<input ng-disabled=""
type="password"
name="confirmPassword"
placeholder="Confirm password"
ng-model="password.confirm"
ng-match="password.new"
required>
<span ng-show="changePasswordForm.confirmPassword.$error.match">
New and confirm do not match
</span>
<div>
<button type="submit"
ng-disabled="changePasswordForm.$invalid"
ng-click="changePassword(password.new, changePasswordForm);reset();">
Change password
</button>
</div>
</form>
I have created plunker with solution that works perfect for me. It uses custom directive but on entire form and not on single field.
http://plnkr.co/edit/HnF90JOYaz47r8zaH5JY
I wouldn't recommend disabling submit button for server validation.
Ok. In case if someone needs working version, it is here:
From doc:
$apply() is used to enter Angular execution context from JavaScript
(Keep in mind that in most places (controllers, services)
$apply has already been called for you by the directive which is handling the event.)
This made me think that we do not need: $scope.$apply(function(s) { otherwise it will complain about $digest
app.directive('uniqueName', function($http) {
var toId;
return {
require: 'ngModel',
link: function(scope, elem, attr, ctrl) {
//when the scope changes, check the name.
scope.$watch(attr.ngModel, function(value) {
// if there was a previous attempt, stop it.
if(toId) clearTimeout(toId);
// start a new attempt with a delay to keep it from
// getting too "chatty".
toId = setTimeout(function(){
// call to some API that returns { isValid: true } or { isValid: false }
$http.get('/rest/isUerExist/' + value).success(function(data) {
//set the validity of the field
if (data == "true") {
ctrl.$setValidity('uniqueName', false);
} else if (data == "false") {
ctrl.$setValidity('uniqueName', true);
}
}).error(function(data, status, headers, config) {
console.log("something wrong")
});
}, 200);
})
}
}
});
HTML:
<div ng-controller="UniqueFormController">
<form name="uniqueNameForm" novalidate ng-submit="submitForm()">
<label name="name"></label>
<input type="text" ng-model="name" name="name" unique-name> <!-- 'unique-name' because of the name-convention -->
<span ng-show="uniqueNameForm.name.$error.uniqueName">Name is not unique.</span>
<input type="submit">
</form>
</div>
Controller might look like this:
app.controller("UniqueFormController", function($scope) {
$scope.name = "Bob"
})
Thanks to the answers from this page learned about https://github.com/webadvanced/ng-remote-validate
Option directives, which is slightly less than I do not really liked, as each field to write the directive.
Module is the same - a universal solution.
But in the modules I was missing something - check the field for several rules.
Then I just modified the module https://github.com/borodatych/ngRemoteValidate
Apologies for the Russian README, eventually will alter.
I hasten to share suddenly have someone with the same problem.
Yes, and we have gathered here for this...
Load:
<script type="text/javascript" src="../your/path/remoteValidate.js"></script>
Include:
var app = angular.module( 'myApp', [ 'remoteValidate' ] );
HTML
<input type="text" name="login"
ng-model="user.login"
remote-validate="( '/ajax/validation/login', ['not_empty',['min_length',2],['max_length',32],'domain','unique'] )"
required
/>
<br/>
<div class="form-input-valid" ng-show="form.login.$pristine || (form.login.$dirty && rv.login.$valid)">
From 2 to 16 characters (numbers, letters and hyphens)
</div>
<span class="form-input-valid error" ng-show="form.login.$error.remoteValidate">
<span ng:bind="form.login.$message"></span>
</span>
BackEnd [Kohana]
public function action_validation(){
$field = $this->request->param('field');
$value = Arr::get($_POST,'value');
$rules = Arr::get($_POST,'rules',[]);
$aValid[$field] = $value;
$validation = Validation::factory($aValid);
foreach( $rules AS $rule ){
if( in_array($rule,['unique']) ){
/// Clients - Users Models
$validation = $validation->rule($field,$rule,[':field',':value','Clients']);
}
elseif( is_array($rule) ){ /// min_length, max_length
$validation = $validation->rule($field,$rule[0],[':value',$rule[1]]);
}
else{
$validation = $validation->rule($field,$rule);
}
}
$c = false;
try{
$c = $validation->check();
}
catch( Exception $e ){
$err = $e->getMessage();
Response::jEcho($err);
}
if( $c ){
$response = [
'isValid' => TRUE,
'message' => 'GOOD'
];
}
else{
$e = $validation->errors('validation');
$response = [
'isValid' => FALSE,
'message' => $e[$field]
];
}
Response::jEcho($response);
}