npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

pp-validator

v1.0.40

Published

Validator input of data

Downloads

58

Readme

Plugin pp-validator

Plugin de validação de entrada de dados em javascript.

  • Este plugin esta no repositorio do NPM, aqui .

Instalação

Requer Node.js

  • npm i pp-validator
  • Import a lib para o projeto com a tag
<script: src="your_path_node_modules/pp-validator/dist/bundle.js"></script>

Como Usar

Crie um objeto com a propriedade obrigatória 'validators' do tipo array com a quantidade de elementos que queira validar, passando 2 propriedades para cada nó.

element

-- O elemento DOM do html. -- Precisa definir o name nos inputs para o retorno correto do input validado. -- Nesse exemplo a busca dos elementos foi feita em cima do name, mas pode ser de qualquer outra forma, (id, classes, etc..)

rules

-- Array de regras para o elemento em questão ser validado. -- Exemplo de apenas uma regra especifica: ['isCpfOrCnpj']. obs: Nesse caso não precisa validar se é vazio, regras especificas ja fazem isso. -- Exemplo com varias regras: ['isNotEmpty', 'IsString']

response

-- Permite escrever uma mensagem personalizada para facilitar na hora de mostrar a mensagem para o usuário sobre aquele erro no campo especifico

PluginValidator

Ao construir o objeto com as validações, invoque a o serviço PluginValidator passando os argumentos.

let result = PluginValidator( args );   
console.log(result);
Inputs

No Html:

   <div class="column">
       <label for="name">NOME</label>
       <input name="name" type="text" id="name">
   </div>
   
   <div class="column">
       <label for="name">IDADE</label>
       <input name="age" type="text" id="age">
   </div>

   <div class="column">
       <label for="CPF">CPF / CNPJ</label>
       <input name="cpf" type="text" id="cpf">
   </div>

   <div class="column">
       <label for="phone">TELEFONE</label>
       <input name="phone" type="text" id="phone">
   </div>

   <div class="column">
       <label for="cellphone">CELULAR</label>
       <input name="cellphone" type="text" id="cellphone">
   </div>

   <div class="column">
       <label for="DATA">DATA INPUT TYPE DATE</label>
       <input name="date" type="date" id="date">
   </div>
   
   <div class="column">
       <label for="DATA">DATA INPUT TYPE TEXT</label>
       <input name="date_text" type="text" id="date_text">
   </div>

   <div class="column">
       <label for="DATA">ANIVERŚARIO TYPE DATE</label>
       <input name="birthday_date" type="date" id="birthday_date">
   </div>

   <div class="column">
       <label for="DATA">ANIVERŚARIO TYPE TEXT</label>
       <input name="birthday" type="text" id="birthday">
   </div>

   <div class="column">
       <select name="options" id="options">
           <option value="0">Selecione</option>
           <option value="1">Me escolha :)</option>
           <option value="2">Não! escolha eu :~)</option>
       </select>
   </div>

   <div class="column">
       <button type="button" onclick="toDo()">validar</button>
   </div>       
Código javascript

No Javascript

 function toDo() 
    {
        let args = {

                'validators': [
                    { 
                        'element': document.querySelector('input[name=name]'),
                        'rules': ['isNotEmpty', 'isString', 'isFullName'],
                        'response': 'Digite seu nome completo!'
                    },
                    { 
                        'element': document.querySelector('input[name=age]'),
                        'rules': ['isNotEmpty', 'isInt'],
                        'response': 'Campo não pode ser vazio!'
                    },
                    { 
                        'element': document.querySelector('input[name=cpf]'),
                        'rules': ['isCpfOrCnpj'],
                        'response': 'CPF/CNPJ inválido!'
                    },
                    { 
                        'element': document.querySelector('input[name=date]'),
                        'rules': ['isDate'],
                        'response': 'Data inválida!'
                    },
                    { 
                        'element': document.querySelector('input[name=date_text]'),
                        'rules': ['isDate'],
                        'response': 'Data inválida!'
                    },
                    { 
                        'element': document.querySelector('input[name=phone]'),
                        'rules': ['isPhone'],
                        'response': 'Telefone inválido!'
                    },
                    { 
                        'element': document.querySelector('input[name=cellphone]'),
                        'rules': ['isCellphone'],
                        'response': 'Celular inválido!'
                    },
                    { 
                        'element': document.querySelector('input[name=birthday_date]'),
                        'rules': ['isOfAge'],
                        'response': 'Para acessar você precisa ter mais de 18 anos!'
                    },
                    { 
                        'element': document.querySelector('input[name=birthday]'),
                        'rules': ['isOfAge'],
                        'response': 'Para acessar você precisa ter mais de 18 anos!'
                    },
                    { 
                        'element': document.querySelector('#options'),
                        'rules': ['isNotEmpty'],
                        'response': 'Selecione uma opção!'
                    },
                ]
            }   
            
        let result = PluginValidator( args );   
Resultado

Retorna um objeto com resultado das validações

[{"name":"name","valid":false},{"name":"age","valid":false},{"name":"cpf","valid":false},{"name":"date","valid":false},{"name":"date_text","valid":false}, isValid: false]
Atenção

Se alguma validação falhar, a propriedade isValid retornara false, caso contratio retornara true, facilitando a iteração pelo objeto, caso não precise buscar o nome do elemento que fracassou na validação.

Lista de Regras

Essas são as regras atualmente, podendo crescer como a necessidade de novas implementações.

| Plugin | README | | ------ | ------ | | isString | Verifica se é do tipo String. | | isInt | Verifica se é do tipo Int. | | isNotEmpty | Verifica se é não é undefined/vazio/null e maior que 0 para elementos do tipo select. | | isCpf | Verifica se é um CPF Válido | | | Se vier com mascara, a função já remove. | | isCnpj | Verifica se é um CNPJ. | | | Se vier com mascara, a função já remove. | | | Obs.: apenas verifica a quantidade de caracteres do input por enquanto | | isCpfOrCnpj | Verifica se é um CPF/CNPJ. | | | Se vier com mascara, a função já remove. | | | CPF.: verifica se é um cpf válido | | | CNPJ.: apenas verifica a quantidade de caracteres do input por enquanto | | isDate | Verifica se é uma DATA valida. | | | Campo input do tipo TEXT/DATE | | | Obs.: caso o input for do tipo text, o formato de envio deve ser 01/01/2020. | | isZipCode | Verifica se é um CEP valido. | | | Se vier com mascara, a função já remove. | | | ex: 17512090 | | | Obs.: apenas verifica a quantidade de caracteres do input | | isPhone | Verifica se é um TELEFONE valido. | | | ex: XX XXXX-XXXX | | | Se vier com mascara, a função já remove. | | | Valida números repetidos ex: (33 3333-3333) | isCellphone | Verifica se é um CELLPHONE valido. | | | ex: XX XXXXX-XXXX | | | Se vier com mascara, a função já remove. | | | Valida números repetidos ex: (33 99999-9999). | | isOfAge | Verifica se é menor de idade. | | | Campo input do tipo TEXT/DATE | | isFullName | Verifica quantide de palavras | | | Campo input do tipo TEXT | | | Exemplo validado: (ana Julia) 2 palavras retorna true | | | Exemplo não validado: (Ana) 1 palavras retorna false |

License

MIT