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

@kra/validator

v0.1.5

Published

Validator for js

Downloads

14

Readme

Validator for JavaScript

version 0.1.0

Install

$ yarn add @kra/validator

Guide

import Validator from '@kra/validator'

// [1] Define validation rules 
const rules = {
  email: 'required|email|max:100',
  password: 'required|max:255'
}

// [2] Define options messages
const options = {
  messages : {
    required: ':attribute は必須項目です。',
    email: 'メールアドレスの形式が違います。',
    max: ':attribute の文字数は :value 以下で入力してください。'
  }
}

// [3] Create validator instance
const validator = new Validator(rules, options)

// [4] Lets validate
const errros = validator.validate('email', '[email protected]')

if (errors.email) {
    // has email error
    console.log(errors.email.message)
} else {
    // not error
}

Error Object

{
    'aRule': {
        attribute,
        constraint,
        message,
        parameters
    },
    ...
}

Rules

Rules: ルール stringで以下のように表す email: required|email|between:5,20

ルール名はキーで表し、制約はパイプ(|)で区切る。 制約はコロン(:)とカンマ(,)でそのパラメータを表す。

regex では配列を利用してください。
postcode: ['required', 'regex:/[0-9]{3}-[0-9]{4}/']

  • Constraint: 制約

Constraint一覧

  • between between:<min>,<max>
  • email email
  • max max:<value>
  • regex regex:<RegExp>
  • required required
  • numeric numeric
  • confirmed confirmed:<field> ex:
const rules = {
  password: 'required|between:5,255',
  passwordConfirmed: 'required|between:5,255|confirmed:password'
}

APIs

  • validate(attribute: string, input: string): object

  • getRules(): array<Rule>

  • getRule(attribute: string): Rule

  • getErrors(): object

  • getError(attribute): object

  • hasErrors(): boolean

  • hasError(attribute): boolean

  • removeErrors(): void

  • clear(): void

with React

Class Component:

import React from 'react'
import Validator from '@kra/validator' 

// [1] Define validation rules 
const rules = {
  email: 'required|email|max:15',
  password: 'required|max:255'
}

// [2] Define error messages
// :attribute is validation rule key
// :value is validation rules parameter name
const messages = {
  required: ':attributeは必須項目です。', // ex: メールアドレスは必須項目です。
  email: 'メールアドレスの形式が違います。',
  max: ':attributeの文字数は :value 以下で入力してください。' // ex: パスワードの文字数は 255 以下で入力してください。
}

// [3] Define custom attributes
const attributes = {
  email: 'メールアドレス',
  password: 'パスワード'
}

// [4] Create validator instance
const validator = new Validator(rules, { messages, attributes })

class SomeComponent extends React.Component {
  state = {
    errors: {}
  }

  handleChange = type => event => {
    const errors = validator.validate(type, event.target.value)
    this.setState({
      errors: errors
    })
  }
  
  render() {
    const {
      errors
    } = this.state
  
    return (
      <SomeForm>
        <InputEmail 
          error={Boolean(errors.email)}
          helperText={errors.email && errors.email.message}
        />
        <InputPassword
          error={Boolean(errors.password)}
          helperText={errors.password && errors.email.password}
        />
      </SomeForm>
    )
  } 

}

Make hooks

ex:makeValidate.js

import { useState } from 'react'
import Validator from '@kra/validator'

const makeValidate = (rules, options) => {
  const validator = new Validator(rules, options)

  const useValidate = () => {
    const [errors, setErros] = useState({})
    const validate = inputs => {
      const result = validator.validateMap(inputs)
      setErros(result)
      return Object.keys(result).length === 0
    }

    return [errors, validate]
  }

  return useValidate
}

export default makeValidate

use hook

import React from 'react'
import TextField from '@material-ui/core/TextField'
import makeValidate from 'path/to/makeValidate'

const rules = {
  email: 'required|email|max:255',
  password: 'required|between:5,255'
}

const messages = {
  required: ':attributeは必須項目です',
  email: ':attributeの形式が違います',
  max: ':attributeの文字数は:value文字以下で入力してください',
  between: ':min文字以上、:max文字以下で入力して下さい'
}

const attributes = {
  email: 'メールアドレス',
  password: 'パスワード'
}

const useValidate = makeValidate(rules, { messages, attributes })

const SimpleForm = props => {
  const [errors, validate] = useValidate()

  const handleChange = type => event => {
    validate(type, event.target.value)
  }

  return (
    <form>
      <TextField
        error={Boolean(errors.name)}
        helperText={errors.name && errors.name.message}
        label='email'
        onChange={handleChange('email')}
        type='email'
      />
      <TextField
        error={Boolean(errors.email)}
        helperText={errors.email && errors.email.message}
        label='passworc'
        onChange={handleChange('password')}
        type='password'
      />
    </form>
  )
}

Custom Constraint

import { Constraint } from '@kra/validator'

class PostcodeConstraint extends Constraint {
  get name() {
    return 'postcode'
  }

  get message() {
    return ':attribute は 000-0000 の形式で入力してください'
  }

  valid(input) {
    return Boolean(input.match(/^[0-9]{3}-[0-9]{4}$/))
  }
}

const validator = new Validator(rules, {
  constraints: {
    postcode: PostcodeConstraint,
    ...
  }
})

LICENCE

MIT