Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { Injectable } from '@angular/core';
- import * as moment from 'moment';
- import 'moment/locale/pt-br';
- import {
- FormGroup,
- FormControl,
- FormBuilder,
- Validators,
- } from '@angular/forms';
- @Injectable()
- export class FormValidationsService {
- checkInvalidTouched(form: FormGroup, field: string) {
- return (
- !form.get(field).valid &&
- (form.get(field).touched || form.get(field).dirty)
- );
- }
- //Função praa a validação de data
- isDateValid(form: FormGroup, field: string) {
- let date = form.get(field).value;
- if (date != null) {
- let dateOfBirth = moment(date, "DD-MM-YYYY","pt-br");
- if(moment(dateOfBirth).isValid() && date.length === 10) {
- if(moment(dateOfBirth).isBefore(moment.now()))
- return true;
- else
- return false;
- }
- else {
- return false;
- }
- }
- }
- //Função para a validação do Email
- isEmailValid(form: FormGroup, field: string): string {
- if(form.get(field).value == "" && !form.get(field).valid) {
- return "empty";
- }
- else if(!form.get(field).valid && form.get(field).value != "" && form.get(field).dirty) {
- return "invalid";
- }
- }
- //Função para a validação do Telefone
- isPhoneValid(form: FormGroup, field: string) {
- let phone = form.get(field).value;
- if (phone != null) {
- if (phone.length >= 10)
- return true;
- else
- return false;
- }
- }
- //Função para a validação do CPF
- isCPFValid(form: FormGroup, field: string) : boolean
- {
- let cpf = form.get(field).value;
- if (cpf != null) {
- let numeros, digitos, soma, i, resultado, digitos_iguais;
- digitos_iguais = 1;
- if (cpf.length < 11)
- return false;
- for (i = 0; i < cpf.length - 1; i++)
- if (cpf.charAt(i) != cpf.charAt(i + 1))
- {
- digitos_iguais = 0;
- break;
- }
- if (!digitos_iguais)
- {
- numeros = cpf.substring(0,9);
- digitos = cpf.substring(9);
- soma = 0;
- for (i = 10; i > 1; i--)
- soma += numeros.charAt(10 - i) * i;
- resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
- if (resultado != digitos.charAt(0))
- return false;
- numeros = cpf.substring(0,10);
- soma = 0;
- for (i = 11; i > 1; i--)
- soma += numeros.charAt(11 - i) * i;
- resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
- if (resultado != digitos.charAt(1))
- return false;
- return true;
- }
- else
- return false;
- }
- }
- applyErrorCss(form: FormGroup, field: string) {
- return {
- 'form__field--error': this.checkInvalidTouched(form, field),
- };
- }
- validateAllFormFields(formGroup: FormGroup) {
- Object.keys(formGroup.controls).forEach(field => {
- const control = formGroup.get(field);
- if (control instanceof FormControl) {
- control.markAsTouched({ onlySelf: true });
- } else if (control instanceof FormGroup) {
- this.validateAllFormFields(control);
- }
- });
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement