패키지, 저장소 및 앱 카테고리 검색

패키지 상세v2.0.1

verify

검증을 간단하게 만듭니다. 확장 기반의 상태 검증 DSL입니다.

AndroidiOSWebmacOSWindowsLinux
30일 다운로드
61
좋아요
55
Pub 점수
140

패키지 설치

flutter pub add verify

패키지 개요

공개 정보를 바탕으로 생성한 선택 가이드입니다.

Verify는 직관적인 확장 기반 DSL을 통해 폼 및 상태 검증을 단순화하는 Flutter/Dart 패키지입니다. 개발자는 데이터 유형 위에서 플루언트 구문을 사용하여 검증 규칙을 간결하게 정의할 수 있습니다. 이 패키지는 사용자 정의 가능한 검증 로직을 지원하며, 봐일러플레이트 코드 없이 기존 워크플로우에 원활하게 통합됩니다. 사용 편의성을 고려해 설계되어 여러 플랫폼에서 검증 로직의 가독성과 유지보수성을 향상시킵니다.

사용 사례

  • 양식 입력 검증
  • UI 컴포넌트에서 상태 검증
  • 실시간 사용자 피드백
  • 사용자 정의 검증 규칙
  • 크로스 플랫폼 검증
  • 복잡한 검증 로직 간소화

주요 기능

  • 확장 기반의 DSL
  • 최소한의 보일러플레이트
  • 체인 가능한 검증 메서드
  • 사용자 정의 검증기를 지원합니다
  • 모든 플러터 플랫폼에서 작동합니다
  • 기존 코드와의 간편한 통합

적합한 대상

  • 간단한 검증을 원하는 개발자
  • 클린 코드를 우선시하는 팀
  • 광범위한 폼 입력을 포함하는 앱
  • 다중 플랫폼을 대상으로 하는 프로젝트
  • 프론트엔드 중심의 플러터 애플리케이션

고려 사항

  • 기본 검증 패턴에 한정됨
  • 내장된 국제화 없음
  • Dart 확장에 대한 이해 필요
  • 매우 동적인 검증 로직에 적합하지 않음
  • 복잡한 시나리오를 위해 추가 설정이 필요할 수 있습니다

원본 README

연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.

Validations made simple

Build Status Pub Package Codecov MIT License

A fp inspired validation DSL. For Dart and Flutter projects.

Features

  • Completely extensible (create your own combinators, validator primitives, etc)
  • Flexible Verify is an extension based API (There is not single class created its all pure functions)
  • Customizable (Define you own error types if required) organize validators how ever you want
  • Bloc friendly (See examples for a concrete implementation)
  • Null safe (as a prerelease)

Usage

Creating validators

A Validator is just a simple function alias:

// One of 2 variats depending on wether the validated subject will be transformed into another type or not
typedef ValidatorT<S, T> = Either<List<dynamic>, T> Function(S subject);
typedef Validator<S> = Either<List<dynamic>, S> Function(S subject);

So you can create your own validator by just specifying a function for example:

final Validator<String> emailValidator = (String email) {
  return email.contains('@') ? Right(email) : Left('Bad email format')
};

Create simple validators from predicates

A simpler way is to use some of the built in helpers.

final contains@ = Verify.that(
  (String email) => email.contains('@'),
    error: 'Bad email format'
    );

Use custom errors and filter them by type

Reuse validators

Use composition to build up more complex validators.

final Validator<String> emailValidator = Verify.all([ contains@, notEmpty ])
Validate and transform

Validators are also capable of transforming their input, so for instance we can do parsing and validation in one go.

final Validator<String, int> intParsingValidator = (String str) => Right(int.parse(str));

final validator = intParsingValidator.onException((_) => Error('not an integer'));
Field validations

Given a model, for instance a user:

class User extends Equatable {
  final String? phone;
  final String? mail;
  final int? age;

  const User(this.phone, this.mail, this.age);

  @override
  List<Object> get props => [phone ?? '', mail ?? '', age ?? ''];
}

Additional checks can be performed on the object and its fields by chaining a series of check and checkField methods.

final userValidator = Verify.empty<User>()
    .check((user) => !user.phone!.isEmpty, error: Error('phone empty'))
    .checkField((user) => user.mail!, emailValidator);

final someUser = User('','', 25);
final Either<List<Error>, User> validationResult = userValidator.verify(someUser);

Note: The difference between check and checkField is that the later ignore the verification when the value is null, this will likely change in next version supporting null safety.

Run a validator

Running a validator is a simple as passing in a parameter since its just a function. To be a bit more eloquent a verify method is provided, this method is special because besides forwarding the argument to the calling validator it can also be used to filter the error list and have it cast to a specific error type. Just supply a specific type parameter.

final signUpValidation = Verify.subject<SignUpState>();
final errors = signUpValidation
    .verify<SignUpError>(newState); // Either<List<SignUpError>, SignUpState>
Built in validators

Verify doesn't come with many built in validators, because they are so simple to create.

It does come with some regex shorthands.

final validator = Verify.fromRegex(RegExp(r"(^\d+$)", error: Error('not just digits')) // Validator<String, int>
Form validation

Often times you will have modeled your error type similar to:

enum FormField {
  email,
  password,
  passwordConfirmation,
}

class SignUpError extends ValidationError {
  final String message;
  final FormField field;

  SignUpError(this.message, {required this.field});

  @override
  String get errorDescription => message;
}

In these scenarios its convenient to be able to group errors by field.

The solution verify provides for this is:

final validator = Verify.inOrder<SignUpFormState>([
  validateMail,
  validatePassword,
  validateConfirmation,
]);

final Map<FormField, SignUpError> errorMap = validator
    .verify<SignUpError>(someState)
    .errorsGroupedBy((error) => error.field);

Sequencing

A slightly different API can be used to achieve the same results as the inOrder composition function.

final numberValidator = Verify.subject<int>()
  .then(Verify.that(
    (subject) => subject % 2 == 0,
    error: Error('not even'),
  ))
  .then(Verify.that(
    (subject) => subject >= 10,
    error: Error('single digit'),
  ));

final errors2 = numberValidator.errors(3); // yields 1 error
final errors = numberValidator.errors(4); // yields 1 error

This way you have quick access to errors segmented by field.

카테고리

의존성

의존성 목록 2 개

소스 저장소

이 패키지를 사용하는 프로젝트

아직 데이터가 없습니다.