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

패키지 상세v0.0.9

helium_validator

Flutter용 가볍고 강력하며 확장 가능한 검증 라이브러리입니다.

AndroidiOSWebmacOSWindowsLinux
30일 다운로드
15
좋아요
3
Pub 점수
145

패키지 설치

flutter pub add helium_validator

패키지 개요

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

Helium Validator는 Flutter 애플리케이션을 위한 가볍고 강력하며 확장 가능한 검증 라이브러리입니다. 안드로이드, iOS, 웹, macOS, 윈도우, 리눅스 등 여러 플랫폼에서 사용자 입력을 간단하고 유연하게 검증할 수 있는 방법을 제공합니다. 내장된 검증기와 사용자 정의 규칙 지원을 통해 개발자가 데이터 무결성을 효율적으로 유지할 수 있습니다. 가독성과 통합 용이성을 중시하여 폼, 로그인 화면 및 입력 검증이 필요한 모든 상황에 적합합니다.

사용 사례

  • 폼 검증
  • 사용자 입력 검사
  • 인증 흐름
  • 데이터 무결성 강제 적용
  • 사용자 정의 검증 로직
  • 크로스 플랫폼 검증

주요 기능

  • 경량 설계
  • 확장 가능한 검증 시스템
  • 내장 검증 규칙
  • 사용자 정의 검증기 지원
  • 크로스 플랫폼 호환성
  • Flutter 위젯과의 간편한 통합

적합한 대상

  • 폼을 구축하는 플러터 개발자
  • 강력한 입력 검증이 필요한 앱
  • 코드 유지보수를 우선시하는 팀
  • 다중 플랫폼을 대상으로 하는 프로젝트
  • 최소한의 보일러플레이트를 원하는 개발자

고려 사항

  • 복잡한 규칙은 수동 설정이 필요합니다
  • 기본 예제 외에 문서가 제한적
  • 기존에 상태 관리를 사용하는 프로젝트에 가장 적합
  • 고급 UI 피드백을 위해 추가 패키지가 필요할 수 있습니다
  • 서버 측 검증을 위한 것이 아님

원본 README

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

Helium Validator

A lightweight, powerful, and extensible validation library for Flutter.

If you find this library helpful, please consider supporting me by giving it a star on GitHub.

Preview

Helium Validator Preview

Introduction

Helium Flutter Validator is a powerful and flexible validation library for Flutter.

It provides a fluent API for defining validation rules for strings, numbers, lists, objects, booleans, and dates. You can also extend it to define your own custom validators.

Features
  • Predefined validation rules for common data types.
  • Support for custom validation functions.
  • Lightweight and easy to integrate.
  • Works with flutter forms.
  • Customize error messages.

Installation

To use this validation library in your Dart or Flutter project, follow these steps:

Add the dependency to your pubspec.yaml:

dependencies:
  helium_validator: 0.0.8  

Then, run:

flutter pub get

Getting Started Guide

Basic Example
import 'package:helium_validator/helium_validator.dart';

// define the validator
// chain to add rules
var emailValidator = V.string().required().email();
var ageValidator = V.number().required().min(18);

// use .validate for validation
print(ageValidator.validate('22'));
print(ageValidator.validate('3'));

print(emailValidator.validate("advait@gmail.com"));
print(emailValidator.validate("advaitgmail.com"));

Output :

 null
 Must be at least 18
 null
 Invalid email

The validator will return null, if no validation error occurs, if there is any error it will return the error in string format.

To return all the validation errors you can pass the arg - returnAllErrors = true this will return all the errors as list.

Return all validation errors
import 'package:helium_validator/helium_validator.dart';

// define the validator
var ageValidator = V.number().required().min(18).isPrime();

// use validate for validation
print(ageValidator.validate(returnAllErrors: true, '22'));
print(ageValidator.validate(returnAllErrors: true, '8'));

print(ageValidator.validate(returnAllErrors: true, returnAsList: true, '22'));
print(ageValidator.validate(returnAllErrors: true, returnAsList: true, '8'));

Output:

 Must be a prime number
 Must be at least 18, Must be a prime number
 [Must be a prime number]
 [Must be at least 18, Must be a prime number]

returnAsList if true will return the erros as a list, or as a single string and will comibine mutiple errors in a string/

Using with Flutter forms

The library support direct working with flutter forms, just use .build()

var ageValidator = V.required().min(18);

TextFormField(
decoration: InputDecoration(labelText: 'Age'),
validator: ageValidator.build(),
),

Available Validators

The library has following build in validators

1 String Validators
V.string().required().minLength(3) .maxLength(20).email();  

Available String Validators

required() // Ensures the field is not null or empty
minLength() // Ensures the string has at least [length] characters.
maxLength() // Ensures the string has at most [length] characters.
length() // Ensures the string has exactly [length] characters.
email() /// Validates that the string is a properly formatted email.
url() // Validates that the string is a properly formatted URL.
contains() /// Ensures the string contains the [expected] substring.
startsWith() // /// Ensures the string starts with the given [prefix].
uuid() /// Ensures the string is a valid UUID (v4 format).
datetime() /// Ensures the string is a valid datetime (YYYY-MM-DD HH:mm:ss).
date() /// Ensures the string is a valid date (YYYY-MM-DD).
time() /// Ensures the string is a valid time (HH:mm:ss).
ip() /// Ensures the string is a valid IP address (IPv4 or IPv6).
cidr() /// Ensures the string is a valid CIDR notation.
json() /// Ensures the string is a valid JSON.
ascii() /// Ensures the string contains only ASCII characters.
alpha() /// Ensures the string contains only alphabetic characters (A-Z, a-z).
alphanumeric() /// Ensures the string contains only alphanumeric characters (A-Z, a-z, 0-9).
isNumeric() /// Ensures string contains only numeric digits (0-9)
slug() /// Ensures the string is a valid slug (lowercase,   alphanumeric, hyphens).
creditCard() /// Ensures the string is a valid credit card number.
phoneNumber() /// Ensures the string is a valid phone number.
hexColor() /// Ensures the string is a valid hexadecimal color.
base64() /// Ensures the string is in valid Base64 encoding.
isPalindrome() /// Ensures the string is a palindrome (reads the same forward and backward).
emoji() /// Validates that the string contains at least one emoji.
nanoid() /// Validates that the string is a valid NanoID (alphanumeric, underscore, or hyphen, with at least 10 characters).
cuid() /// Validates that the string is a valid CUID (must start with 'c' followed by at least 24 lowercase alphanumeric characters).
cuid2() /// Validates that the string is a valid CUID2 (24+ lowercase alphanumeric characters, excluding 'c' as the first character).
isoDatetime() /// Validates that the string follows the ISO 8601 datetime format (e.g., "2023-06-29T12:34:56Z").
2 Number Validators
V.number().required().min(18).max(99).positive().even();  

Available Number Validators

required() /// Ensures the value is required (not null or NaN).
min() /// Ensures the value is at least [minValue].
max() /// Ensures the value is at most [maxValue].
positive() /// Ensures the value is positive (> 0).
negative() /// Ensures the value is negative (< 0).
notZero() /// Ensures the value is not zero.
even() /// Ensures the value is an even number.
odd() /// Ensures the value is an odd number.
precision() /// Ensures the value has at most [decimalPlaces] decimal places.
isFinite() /// Ensures the value is a finite number (not infinite or NaN).
isWholeNumber() /// Ensures the value is a whole number (integer).
between() /// Ensures the value is between [minValue] and [maxValue], inclusive.
multipleOf() /// Ensures the value is a multiple of [factor].
safe() /// Ensures the value is within a safe integer range.
isPalindrome() /// Ensures the number is a palindrome (reads the same forward and backward).
isPrime() /// Ensures the number is a prime number.
equalTo() /// Ensures the value is equal to [targetValue].
notEqualTo() /// Ensures the value is not equal to [targetValue].
absoluteValueMax() /// Ensures the absolute value is at most [maxValue].
3 Boolean Validators
V.boolean().isTrue();  

Available Boolean Validators

isTrue() /// Ensures the value is `true`.
isFalse() /// Ensures the value is `false`.
isTruthy() /// Ensures the value is truthy (e.g., "true", "yes", "on", "1").
isFalsy() /// Ensures the value is falsy (e.g., "false", "no", "off", "0").
matches() /// Ensures the value matches a specific boolean expectation.
not() /// Ensures the value does **not** match a specific boolean expectation.
xor() /// Ensures the value follows XOR logic with the given boolean.
equals() /// Ensures the value is exactly equal to the expected boolean.
notNull() /// Ensures the value is not null.

4 List Validators
V.list().minLength(2).maxLength(5).contains("item");  

Available List Validators

minLength() /// Ensures the list has at least [length] items.
maxLength() /// Ensures the list has at most [length] items.
length() /// Ensures the list has exactly [length] items.
unique() /// Ensures all elements in the list are unique.
contains() /// Ensures the list contains [item].
5 Object Validation
V.object({
"name": V.string().required(), "age": V.number().min(18),});  

Available Object Validators

shape() /// Defines the structure of the expected object. Throws an [ArgumentError] if duplicate keys are added.
exactKeys() /// Ensures that only the specified [keys] are allowed in the object.
allowExtraKeys() /// Allows the object to have extra keys beyond the defined schema.
optionalFields() /// Specifies which fields are optional in the object.
nonEmpty() /// Ensures the object is not empty.
customValidation() /// Adds a custom validation rule that checks the entire object.
deepEqual() /// Ensures the object matches the given [other] object exactly.
6 Date Validators
V.object({
"name": V.string().required(), "age": V.number().min(18),});  

Available Date Validators

required() /// Ensures the date is not null or empty.
before() /// Ensures the date is before the given [date].
after() /// Ensures the date is after the given [date].
between() /// Ensures the date falls between [start] and [end].
exact() /// Ensures the date is exactly the given [target] date.
notExact() /// Ensures the date is not exactly the given [target] date.
weekdayOnly() /// Ensures the date falls on a weekday (Monday–Friday).
futureOnly() /// Ensures the date falls on a weekend (Saturday or Sunday).
pastOnly() /// Ensures the date is in the past.

Customize

You can customize your error messages.

Basic Example
import 'package:helium_validator/helium_validator.dart';

  // define the validator
  var emailValidator = V.string().required().email(message: "Please Enter a valid email");
  var ageValidator = V.number().required().min(18, message: "You must be 18 or older to register");

    // use .validate for validation
    print(ageValidator.validate('22'));
    print(ageValidator.validate('3'));

    print(emailValidator.validate("advait@gmail.com"));
    print(emailValidator.validate("advaitgmail.com"));

Output :

I/flutter ( 5192): null
I/flutter ( 5192): You must be 18 or older to register
I/flutter ( 5192): null
I/flutter ( 5192): Please Enter a valid email

Custom Validator

Create your own custom validator

Basic Example
import 'package:helium_validator/helium_validator.dart';

  // define the validator
    final passwordValidator = V.custom()
      ..addRule((value) => (value ?? "").isEmpty ? "Password is required" : null)
      ..addRule((value) => (value?.length ?? 0) < 8 ? "Password must be at least 8 characters" : null)
      ..addRule((value) => !RegExp(r'[A-Z]').hasMatch(value ?? "") ? "Must contain an uppercase letter" : null)
      ..addRule((value) => !RegExp(r'[0-9]').hasMatch(value ?? "") ? "Must contain a number" : null)
      ..addRule((value) => !RegExp(r'[!@#$%^&*(),.?":{}|<>]').hasMatch(value ?? "") ? "Must contain a special character" : null)
      ..addRule((value) => _hasConsecutiveChars(value ?? "") ? "Password must not contain consecutive characters" : null)
      ..addRule((value) => _isCommonPassword(value ?? "") ? "Password is too common" : null);

// Helper method to check if the password is a common password
bool _isCommonPassword(String value) {
  const commonPasswords = [
    "password", "123456", "123456789", "qwerty", "abc123", "password1", "12345", "letmein", "welcome", "admin"
  ];
  return commonPasswords.contains(value.toLowerCase());
}

// Helper method to check for consecutive characters
bool _hasConsecutiveChars(String value) {
  for (int i = 0; i < value.length - 2; i++) {
    if (value.codeUnitAt(i) + 1 == value.codeUnitAt(i + 1) && value.codeUnitAt(i + 1) + 1 == value.codeUnitAt(i + 2)) {
      return true;
    }
  }
  return false;
}

    print(passwordValidator.validate("Short1"));
    print(passwordValidator.validate("testpassword1"));
	print(passwordValidator.validate("abc123"));
    print(passwordValidator.validate("TestPass1@"));

Output :

I/flutter ( 5192): null
I/flutter ( 5192): You must be 18 or older to register
I/flutter ( 5192): null
I/flutter ( 5192): Please Enter a valid email

Composite Validator


title: Composite Validator Example description: Learn how to use the CompositeValidator to combine multiple validation rules.

Example: Using the CompositeValidator

The CompositeValidator allows you to apply multiple validation rules from different validators to a single value.

Code Example

import 'package:helium_validator/helium_validator.dart';

void main() {
  // Create individual validators 
  final numberValidator = V.number().isInteger();
  final rangeValidator = V.number().min(10).max(100);
  // Combine them using CompositeValidator 
  final compositeValidator = CompositeValidator<int>([ numberValidator, rangeValidator, ]);
  // Validate different inputs 
  compositeValidator.validate("25");  // ✅ Valid
  compositeValidator.validate("5");   // ❌ Must be at least 10
  compositeValidator.validate("150"); // ❌ Must be at most 100
  compositeValidator.validate("abc"); // ❌ Invalid number format
}  

Contributing

Contributions are welcome! Feel free to submit issues or pull requests to improve this library.


License

This project is licensed under the MIT License.

카테고리

의존성

의존성 목록 1 개

소스 저장소

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

아직 데이터가 없습니다.