Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save principalweb/21d23a8de1a545fb78e34bf7c18a2850 to your computer and use it in GitHub Desktop.
Save principalweb/21d23a8de1a545fb78e34bf7c18a2850 to your computer and use it in GitHub Desktop.
<md-input-container class="admin-form">
<input md-input placeholder="Block Title" nfNoSpaces [(ngModel)]="block.title" id="block-{{ block.id }}-input-name" name="title"
#title="ngModel">
<md-hint [ngStyle]="{'color': 'red'}" align="start" *ngIf="!title.valid && !title.pristine">Title is required.</md-hint>
</md-input-container>
Be sure to include ref to directive in module declarations array.
import { Directive, Input, OnChanges, SimpleChanges } from '@angular/core';
import { NoWhitespaceValidator } from './no-whitespace.validator';
import { Validator, AbstractControl, Validators, NG_VALIDATORS } from '@angular/forms';
/**
* This validator works like "required" but it does not allow whitespace either
*
* @export
* @class NoWhitespaceDirective
* @implements {Validator}
*/
@Directive({
selector: '[nfNoSpaces]',
providers: [{ provide: NG_VALIDATORS, useExisting: NoWhitespaceDirective, multi: true }]
})
export class NoWhitespaceDirective implements Validator {
private valFn = NoWhitespaceValidator();
validate(control: AbstractControl): { [key: string]: any } {
return this.valFn(control);
}
}
import { AbstractControl } from '@angular/forms';
import { NoWhitespaceValidator } from './no-whitespace.validator';
describe('Whitespace Validator', () => {
let validatorFn = NoWhitespaceValidator();
it('empty string is invalid', () => {
let control = { value: '' }
let result = validatorFn(control as AbstractControl)
expect(result !== null).toBe(true);
expect(result['whitespace']).toBe('value is only whitespace')
});
it('spaces only are invalid', () => {
let control = { value: ' ' }
let result = validatorFn(control as AbstractControl)
expect(result !== null).toBe(true);
});
it('null is invalid', () => {
let control: any = { value: null }
let result = validatorFn(control as AbstractControl)
expect(result !== null).toBe(true);
});
it('text is not considered invalid', () => {
let control = { value: 'i have whitespace on the inside' }
let result = validatorFn(control as AbstractControl)
expect(result).toBe(null);
});
});
import { AbstractControl, ValidatorFn } from '@angular/forms';
export function NoWhitespaceValidator(): ValidatorFn {
return (control: AbstractControl): { [key: string]: any } => {
let isWhitespace = (control.value || '').trim().length === 0;
let isValid = !isWhitespace;
return isValid ? null : { 'whitespace': 'value is only whitespace' }
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment