Giter Club home page Giter Club logo

schema-typed's Introduction

schema-typed

Schema for data modeling & validation

npm GitHub Actions Coverage Status

Table of Contents

Installation

npm install schema-typed --save

Usage

Getting Started

import { SchemaModel, StringType, DateType, NumberType, ObjectType, ArrayType } from 'schema-typed';

const model = SchemaModel({
  username: StringType().isRequired('Username required'),
  email: StringType().isEmail('Email required'),
  age: NumberType('Age should be a number').range(18, 30, 'Over the age limit'),
  tags: ArrayType().of(StringType('The tag should be a string').isRequired()),
  role: ObjectType().shape({
    name: StringType().isRequired('Name required'),
    permissions: ArrayType().isRequired('Permissions required')
  })
});

const checkResult = model.check({
  username: 'foobar',
  email: '[email protected]',
  age: 40,
  tags: ['Sports', 'Games', 10],
  role: { name: 'administrator' }
});

console.log(checkResult);

checkResult return structure is:

{
  username: { hasError: false },
  email: { hasError: false },
  age: { hasError: true, errorMessage: 'Over the age limit' },
  tags: {
    hasError: true,
    array: [
      { hasError: false },
      { hasError: false },
      { hasError: true, errorMessage: 'The tag should be a string' }
    ]
  },
  role: {
    hasError: true,
    object: {
      name: { hasError: false },
      permissions: { hasError: true, errorMessage: 'Permissions required' }
    }
  }
};

Multiple verification

StringType()
  .minLength(6, "Can't be less than 6 characters")
  .maxLength(30, 'Cannot be greater than 30 characters')
  .isRequired('This field required');

Custom verification

Customize a rule with the addRule function.

If you are validating a string type of data, you can set a regular expression for custom validation by the pattern method.

const model = SchemaModel({
  field1: StringType().addRule((value, data) => {
    return /^[1-9][0-9]{3}\s?[a-zA-Z]{2}$/.test(value);
  }, 'Please enter legal characters'),
  field2: StringType().pattern(/^[1-9][0-9]{3}\s?[a-zA-Z]{2}$/, 'Please enter legal characters')
});

model.check({ field1: '', field2: '' });

/**
{
  field1: {
    hasError: true,
    errorMessage: 'Please enter legal characters'
  },
  field2: {
    hasError: true,
    errorMessage: 'Please enter legal characters'
  }
};
**/

Field dependency validation

  1. Use the equalTo method to verify that the values of two fields are equal.
const model = SchemaModel({
  password: StringType().isRequired(),
  confirmPassword: StringType().equalTo('password')
});
  1. Use the addRule method to create a custom validation rule.
const model = SchemaModel({
  password: StringType().isRequired(),
  confirmPassword: StringType().addRule(
    (value, data) => value === data.password,
    'Confirm password must be the same as password'
  )
});
  1. Use the proxy method to verify that a field passes, and then proxy verification of other fields.
const model = SchemaModel({
  password: StringType().isRequired().proxy(['confirmPassword']),
  confirmPassword: StringType().equalTo('password')
});

Asynchronous check

For example, verify that the mailbox is duplicated

function asyncCheckEmail(email) {
  return new Promise(resolve => {
    setTimeout(() => {
      if (email === '[email protected]') {
        resolve(false);
      } else {
        resolve(true);
      }
    }, 500);
  });
}

const model = SchemaModel({
  email: StringType()
    .isEmail('Please input the correct email address')
    .addAsyncRule((value, data) => {
      return asyncCheckEmail(value);
    }, 'Email address already exists')
    .isRequired('This field cannot be empty')
});

model.checkAsync({ email: '[email protected]' }).then(checkResult => {
  console.log(checkResult);
  /**
  {
    email: {
      hasError: true,
      errorMessage: 'Email address already exists'
    }
  };
  **/
});

Validate nested objects

Validate nested objects, which can be defined using the ObjectType().shape method. E.g:

const model = SchemaModel({
  id: NumberType().isRequired('This field required'),
  name: StringType().isRequired('This field required'),
  info: ObjectType().shape({
    email: StringType().isEmail('Should be an email'),
    age: NumberType().min(18, 'Age should be greater than 18 years old')
  })
});

const user = {
  id: 1,
  name: '',
  info: { email: 'schema-type', age: 17 }
};

model.check(data);

/**
 {
  "id": { "hasError": false },
  "name": { "hasError": true, "errorMessage": "This field required" },
  "info": {
    "hasError": true,
    "object": {
      "email": { "hasError": true, "errorMessage": "Should be an email" },
      "age": { "hasError": true, "errorMessage": "Age should be greater than 18 years old" }
    }
  }
}
*/

Combine

SchemaModel provides a static method combine that can be combined with multiple SchemaModel to return a new SchemaModel.

const model1 = SchemaModel({
  username: StringType().isRequired('This field required'),
  email: StringType().isEmail('Should be an email')
});

const model2 = SchemaModel({
  username: StringType().minLength(7, "Can't be less than 7 characters"),
  age: NumberType().range(18, 30, 'Age should be greater than 18 years old')
});

const model3 = SchemaModel({
  groupId: NumberType().isRequired('This field required')
});

const model4 = SchemaModel.combine(model1, model2, model3);

model4.check({
  username: 'foobar',
  email: '[email protected]',
  age: 40,
  groupId: 1
});

API

SchemaModel

SchemaModel is a JavaScript schema builder for data model creation and validation.

static combine(...models)

A static method for merging multiple models.

const model1 = SchemaModel({
  username: StringType().isRequired('This field required')
});

const model2 = SchemaModel({
  email: StringType().isEmail('Please input the correct email address')
});

const model3 = SchemaModel.combine(model1, model2);

check(data: object)

Check whether the data conforms to the model shape definition. Return a check result.

const model = SchemaModel({
  username: StringType().isRequired('This field required'),
  email: StringType().isEmail('Please input the correct email address')
});

model.check({
  username: 'root',
  email: '[email protected]'
});

checkAsync(data: object)

Asynchronously check whether the data conforms to the model shape definition. Return a check result.

const model = SchemaModel({
  username: StringType()
    .isRequired('This field required')
    .addRule(value => {
      return new Promise(resolve => {
        // Asynchronous processing logic
      });
    }, 'Username already exists'),
  email: StringType().isEmail('Please input the correct email address')
});

model
  .checkAsync({
    username: 'root',
    email: '[email protected]'
  })
  .then(result => {
    // Data verification result
  });

checkForField(fieldName: string, data: object, options?: { nestedObject?: boolean })

Check whether a field in the data conforms to the model shape definition. Return a check result.

const model = SchemaModel({
  username: StringType().isRequired('This field required'),
  email: StringType().isEmail('Please input the correct email address')
});

const data = {
  username: 'root'
};

model.checkForField('username', data);

checkForFieldAsync(fieldName: string, data: object, options?: { nestedObject?: boolean })

Asynchronously check whether a field in the data conforms to the model shape definition. Return a check result.

const model = SchemaModel({
  username: StringType()
    .isRequired('This field required')
    .addAsyncRule(value => {
      return new Promise(resolve => {
        // Asynchronous processing logic
      });
    }, 'Username already exists'),
  email: StringType().isEmail('Please input the correct email address')
});

const data = {
  username: 'root'
};

model.checkForFieldAsync('username', data).then(result => {
  // Data verification result
});

MixedType()

Creates a type that matches all types. All types inherit from this base type.

isRequired(errorMessage?: string, trim: boolean = true)

MixedType().isRequired('This field required');

isRequiredOrEmpty(errorMessage?: string, trim: boolean = true)

MixedType().isRequiredOrEmpty('This field required');

addRule(onValid: Function, errorMessage?: string, priority: boolean)

MixedType().addRule((value, data) => {
  return /^[1-9][0-9]{3}\s?[a-zA-Z]{2}$/.test(value);
}, 'Please enter a legal character.');

addAsyncRule(onValid: Function, errorMessage?: string, priority: boolean)

MixedType().addAsyncRule((value, data) => {
  return new Promise(resolve => {
    // Asynchronous processing logic
  });
}, 'Please enter a legal character.');

when(condition: (schemaSpec: SchemaDeclaration<DataType, ErrorMsgType>) => Type)

Conditional validation, the return value is a new type.

const model = SchemaModel({
  option: StringType().isOneOf(['a', 'b', 'other']),
  other: StringType().when(schema => {
    const { value } = schema.option;
    return value === 'other' ? StringType().isRequired('Other required') : StringType();
  })
});

/**
{
  option: { hasError: false },
  other: { hasError: false }
}
*/
model.check({ option: 'a', other: '' });

/*
{
  option: { hasError: false },
  other: { hasError: true, errorMessage: 'Other required' }
}
*/
model.check({ option: 'other', other: '' });

Check whether a field passes the validation to determine the validation rules of another field.

const model = SchemaModel({
  password: StringType().isRequired('Password required'),
  confirmPassword: StringType().when(schema => {
    const { hasError } = schema.password.check();
    return hasError
      ? StringType()
      : StringType().addRule(
          value => value === schema.password.value,
          'The passwords are inconsistent twice'
        );
  })
});

check(value: ValueType, data?: DataType):CheckResult

const type = MixedType().addRule(v => {
  if (typeof v === 'number') {
    return true;
  }
  return false;
}, 'Please enter a valid number');

type.check('1'); //  { hasError: true, errorMessage: 'Please enter a valid number' }
type.check(1); //  { hasError: false }

checkAsync(value: ValueType, data?: DataType):Promise<CheckResult>

const type = MixedType().addRule(v => {
  return new Promise(resolve => {
    setTimeout(() => {
      if (typeof v === 'number') {
        resolve(true);
      } else {
        resolve(false);
      }
    }, 500);
  });
}, 'Please enter a valid number');

type.checkAsync('1').then(checkResult => {
  //  { hasError: true, errorMessage: 'Please enter a valid number' }
});
type.checkAsync(1).then(checkResult => {
  //  { hasError: false }
});

label(label: string)

Overrides the key name in error messages.

MixedType().label('Username');

Eg:

SchemaModel({
  first_name: StringType().label('First name'),
  age: NumberType().label('Age')
});

equalTo(fieldName: string, errorMessage?: string)

Check if the value is equal to the value of another field.

SchemaModel({
  password: StringType().isRequired(),
  confirmPassword: StringType().equalTo('password')
});

proxy(fieldNames: string[], options?: { checkIfValueExists?: boolean })

After the field verification passes, proxy verification of other fields.

  • fieldNames: The field name to be proxied.
  • options.checkIfValueExists: When the value of other fields exists, the verification is performed (default: false)
SchemaModel({
  password: StringType().isRequired().proxy(['confirmPassword']),
  confirmPassword: StringType().equalTo('password')
});

StringType(errorMessage?: string)

Define a string type. Supports all the same methods as MixedType.

isEmail(errorMessage?: string)

StringType().isEmail('Please input the correct email address');

isURL(errorMessage?: string)

StringType().isURL('Please enter the correct URL address');

isOneOf(items: string[], errorMessage?: string)

StringType().isOneOf(['Javascript', 'CSS'], 'Can only type `Javascript` and `CSS`');

containsLetter(errorMessage?: string)

StringType().containsLetter('Must contain English characters');

containsUppercaseLetter(errorMessage?: string)

StringType().containsUppercaseLetter('Must contain uppercase English characters');

containsLowercaseLetter(errorMessage?: string)

StringType().containsLowercaseLetter('Must contain lowercase English characters');

containsLetterOnly(errorMessage?: string)

StringType().containsLetterOnly('English characters that can only be included');

containsNumber(errorMessage?: string)

StringType().containsNumber('Must contain numbers');

pattern(regExp: RegExp, errorMessage?: string)

StringType().pattern(/^[1-9][0-9]{3}\s?[a-zA-Z]{2}$/, 'Please enter legal characters');

rangeLength(minLength: number, maxLength: number, errorMessage?: string)

StringType().rangeLength(6, 30, 'The number of characters can only be between 6 and 30');

minLength(minLength: number, errorMessage?: string)

StringType().minLength(6, 'Minimum 6 characters required');

maxLength(maxLength: number, errorMessage?: string)

StringType().maxLength(30, 'The maximum is only 30 characters.');

NumberType(errorMessage?: string)

Define a number type. Supports all the same methods as MixedType.

isInteger(errorMessage?: string)

NumberType().isInteger('It can only be an integer');

isOneOf(items: number[], errorMessage?: string)

NumberType().isOneOf([5, 10, 15], 'Can only be `5`, `10`, `15`');

pattern(regExp: RegExp, errorMessage?: string)

NumberType().pattern(/^[1-9][0-9]{3}$/, 'Please enter a legal character.');

range(minLength: number, maxLength: number, errorMessage?: string)

NumberType().range(18, 40, 'Please enter a number between 18 - 40');

min(min: number, errorMessage?: string)

NumberType().min(18, 'Minimum 18');

max(max: number, errorMessage?: string)

NumberType().max(40, 'Maximum 40');

ArrayType(errorMessage?: string)

Define a array type. Supports all the same methods as MixedType.

isRequiredOrEmpty(errorMessage?: string)

ArrayType().isRequiredOrEmpty('This field required');

rangeLength(minLength: number, maxLength: number, errorMessage?: string)

ArrayType().rangeLength(1, 3, 'Choose at least one, but no more than three');

minLength(minLength: number, errorMessage?: string)

ArrayType().minLength(1, 'Choose at least one');

maxLength(maxLength: number, errorMessage?: string)

ArrayType().maxLength(3, "Can't exceed three");

unrepeatable(errorMessage?: string)

ArrayType().unrepeatable('Duplicate options cannot appear');

of(type: object)

ArrayType().of(StringType('The tag should be a string').isRequired());

DateType(errorMessage?: string)

Define a date type. Supports all the same methods as MixedType.

range(min: Date, max: Date, errorMessage?: string)

DateType().range(
  new Date('08/01/2017'),
  new Date('08/30/2017'),
  'Date should be between 08/01/2017 - 08/30/2017'
);

min(min: Date, errorMessage?: string)

DateType().min(new Date('08/01/2017'), 'Minimum date 08/01/2017');

max(max: Date, errorMessage?: string)

DateType().max(new Date('08/30/2017'), 'Maximum date 08/30/2017');

ObjectType(errorMessage?: string)

Define a object type. Supports all the same methods as MixedType.

shape(fields: object)

ObjectType().shape({
  email: StringType().isEmail('Should be an email'),
  age: NumberType().min(18, 'Age should be greater than 18 years old')
});

BooleanType(errorMessage?: string)

Define a boolean type. Supports all the same methods as MixedType.

⚠️ Notes

Default check priority:

  • 1.isRequired
  • 2.All other checks are executed in sequence

If the third argument to addRule is true, the priority of the check is as follows:

  • 1.addRule
  • 2.isRequired
  • 3.Predefined rules (if there is no isRequired, value is empty, the rule is not executed)

schema-typed's People

Contributors

choufeng avatar cjex avatar dependabot[bot] avatar imyuanx avatar jspears avatar majo44 avatar saltymonkey avatar sevenoutman avatar simonguo avatar thejian avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

schema-typed's Issues

ArrayType.of type error

SchemaModel({
  numbers: ArrayType().of(
    StringType('asda'),
  ),
})

will throw

Error:(17, 5) TS2345: Argument of type 'StringType<any, string>' is not assignable to parameter of type 'ArrayType<any, string>'.
  Type 'StringType<any, string>' is missing the following properties from type 'ArrayType<any, string>': unrepeatable, of

👇👇👇

of(type: CheckType<any[], DataType, E>) {

type: CheckType<any[], DataType, E> should be type: CheckType<any, DataType, E> ?

thx.

NumberType doesn't accept some valid values

What version of schema-typed are you using?

2.0.2

Describe the Bug

NumberType doesn't accept values with a leading or trailing decimal point as valid. For example '.1' and '1.' are not considered valid.

Expected Behavior

Values with leading and trailing decimal points are valid numbers and should be accepted.

To Reproduce

const model = Schema.Model({
imageScale: NumberType('must be a number'),
});

See screenshot for actual result.
Screen Shot 2022-01-29 at 3 45 32 PM

RegEx for URL doesn't match `mailto:` URL

What version of schema-typed are you using?

5.13.0

Describe the Bug

The regex expression used by the isURL method doesn't match mailto URL e.g. mailto:[email protected]

'^(?!mailto:)(?:(?:http|https|ftp)://|//)(?:\\S+(?::\\S*)?@)?(?:(?:(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[0-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)*(?:\\.(?:[a-z\\u00a1-\\uffff]{2,})))|localhost)(?::\\d{2,5})?(?:(/|\\?|#)[^\\s]*)?$',

Expected Behavior

The above regex should match string mailto:[email protected]

To Reproduce

Test the above regex at https://www.regextester.com/

Suggest add validateOnBlur,validateOnChange and hasError property to the Type and errors

validateOnBlur,validateOnChange it's very usable to describe the schema of the form for the special use, for some case, i build a reack hook form for material. and errors property hasError is very useful for disable the button
eg:
type.js:

class Type {
constructor(name) {
this.name = name;
this.required = false;
this.requiredMessage = '';
this.trim = false;
this.rules = [];
this.priorityRules = []; // Priority check rule

  • this.validateOnBlur = false;
  • this.validateOnChange = false;
    }
    ...
  • // support validateOnChange
  • checkOnBlur = function checkOnBlur(bool = true) {
  • this.validateOnBlur = typeof bool === 'boolean'? bool: false;
    return this;
    };
  • // support validateOnBlur
  • checkOnChange = function checkOnBlur(bool = true) {
  • this.validateOnChange = typeof bool === 'boolean'? bool: false;
  • return this;
    }

schema.js
check = function check(data) {
const _this = this;

  • const checkResult = { hasError:false };
    Object.keys(this.schema).forEach(function (key) {
    checkResult[key] = _this.checkForField(key, data[key], data);
    // easy to define whether the submitBtn is valid
  • checkResult.hasError === false && (checkResult.hasError = checkResult[key].hasError);
    });
    return checkResult;
    };

checkAsync = function checkAsync(data) {
const _this2 = this;

  • const checkResult = { hasError: false };
    const promises = [];
    const keys = [];
Object.keys(this.schema).forEach(function (key) {
  keys.push(key);
  promises.push(_this2.checkForFieldAsync(key, data[key], data));
});

return Promise.all(promises).then(function (values) {
  for (let i = 0; i < values.length; i += 1) {
    checkResult[keys[i]] = values[i];
    // easy to define whether the submitBtn is valid
  •  checkResult.hasError === false && (checkResult.hasError = checkResult[keys[i]].hasError);
    }
    return checkResult;
    

    });
    };

    return Schema;
    }

Something like a "map" Datatype

I would like to use your tool to check my config input for consistency with the expectation :-).
They contain a lot of key value pairs (sometimes called maps), so i just want to check for that user type,
that ALL key have one defined datatype.

Is there a little bit more sophistic solution than this

const model = SchemaModel({
  map: ObjectType().addRule((value, data) => {
    let result = true;
    for (const k in value) {
      if (typeof value[k] != "string") result = false; 
    }
    return result;
  },"must be a set of keys with strings as values")
});

What would be nice, to use your type checking possiblities, so not the native ones, and the error message is now for the complete map and not for the key. As i although have maps of config objects a recursion would be great.

无法做到异步校验

场景:某个值一定需要通过一个接口,或者一些异步的方法进行校验。现在没办法做到。。

推荐使用 结合 async/await 与 Promise 的 resolve 表示校验成功 与 reject 表示校验失败 来实现。

schemaSpec is undefined for .when() inside ObjectType

What version of schema-typed are you using?

2.1.3

Describe the Bug

If using the "when" method within an ObjectType, the schemaSpec variable that is passed to the method is undefined.

Expected Behavior

schemaSpec that is passed to the when method should be populated with the schema of the model.

To Reproduce

Working example without ObjectType: https://stackblitz.com/edit/typescript-jkedsj?file=index.ts
Bug example: https://stackblitz.com/edit/typescript-yv9jop?file=index.ts

ObjectType 希望能添加支持嵌套

One-line summary [问题简述]

希望能为 ObjectType 添加支持嵌套描述的功能,类似于 React 的 Proptype

Expected behaviour [期望结果]

ObjectType 希望能添加支持嵌套

addRule 执行顺序不正确

addRule 执行顺序不正确,超过3个以上的规则,addRule 的执行优先级会高于普通的后续规则

DateType not a valid function - Form Validation

What version of schema-typed are you using?

"rsuite": "^5.22.0", Nov 13, 2022 - likely 2.0.3

Describe the Bug

I am validating a form date value and Am getting DateType is not a function error in ReactJS.
I followed the guidance here but, nothing works.

I'm surprised that the documentation under form validation skipped and did not include date values, why?

Expected Behavior

Show validation message when submit button is clicked Date field is not supplied. - Currently, this is working for String and Number Type, except DateType & MixedType.

To Reproduce

const model = Schema.Model({
startDate: DateType().isRequired('This field is required.'),
})

<Form.Group controlId="start-date-7">
  <Form.HelpText>
    Start date
    <Form.HelpText tooltip>Valid Start Date</Form.HelpText>
  </Form.HelpText>
  <Form.Control name="startDate" style={{ width: 160 }} accepter={DatePicker} />
</Form.Group>

Warning: Failed to parse source map

What version of schema-typed are you using?

2.1.1

Describe the Bug

Probably this package ships ship misconfigured source map. See also facebook/create-react-app#11752.

To Reproduce

  1. Crate an app using create-react-app.
  2. Add rsuite as a dependency.
  3. Try to start or build the app, e.g. by yarn run start.

Actual Behavior

"C:\Program Files (x86)\Yarn\bin\yarn.cmd" run start
[...]

WARNING in ./node_modules/schema-typed/es/ArrayType.js
Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
Failed to parse source map from 'C:\project\node_modules\schema-typed\src\ArrayType.ts' file: Error: ENOENT: no such file or directory, open 'C:\project\node_modules\schema-typed\src\A
rrayType.ts'

WARNING in ./node_modules/schema-typed/es/BooleanType.js
Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
Failed to parse source map from 'C:\project\node_modules\schema-typed\src\BooleanType.ts' file: Error: ENOENT: no such file or directory, open 'C:\project\node_modules\schema-typed\src
\BooleanType.ts'

WARNING in ./node_modules/schema-typed/es/DateType.js
Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
Failed to parse source map from 'C:\project\node_modules\schema-typed\src\DateType.ts' file: Error: ENOENT: no such file or directory, open 'C:\project\node_modules\schema-typed\src\Da
teType.ts'

WARNING in ./node_modules/schema-typed/es/MixedType.js
Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
Failed to parse source map from 'C:\project\node_modules\schema-typed\src\MixedType.ts' file: Error: ENOENT: no such file or directory, open 'C:\project\node_modules\schema-typed\src\M
ixedType.ts'

WARNING in ./node_modules/schema-typed/es/NumberType.js
Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
Failed to parse source map from 'C:\project\node_modules\schema-typed\src\NumberType.ts' file: Error: ENOENT: no such file or directory, open 'C:\project\node_modules\schema-typed\src\
NumberType.ts'

WARNING in ./node_modules/schema-typed/es/ObjectType.js
Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
Failed to parse source map from 'C:\project\node_modules\schema-typed\src\ObjectType.ts' file: Error: ENOENT: no such file or directory, open 'C:\project\node_modules\schema-typed\src\
ObjectType.ts'

WARNING in ./node_modules/schema-typed/es/Schema.js
Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
Failed to parse source map from 'C:\project\node_modules\schema-typed\src\Schema.ts' file: Error: ENOENT: no such file or directory, open 'C:\project\node_modules\schema-typed\src\Sche
ma.ts'

WARNING in ./node_modules/schema-typed/es/StringType.js
Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
Failed to parse source map from 'C:\project\node_modules\schema-typed\src\StringType.ts' file: Error: ENOENT: no such file or directory, open 'C:\project\node_modules\schema-typed\src\
StringType.ts'

WARNING in ./node_modules/schema-typed/es/index.js
Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
Failed to parse source map from 'C:\project\node_modules\schema-typed\src\index.ts' file: Error: ENOENT: no such file or directory, open 'C:\project\node_modules\schema-typed\src\index
.ts'

WARNING in ./node_modules/schema-typed/es/locales/default.js
Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
Failed to parse source map from 'C:\project\node_modules\schema-typed\src\locales\default.ts' file: Error: ENOENT: no such file or directory, open 'C:\project\node_modules\schema-typed
\src\locales\default.ts'

WARNING in ./node_modules/schema-typed/es/locales/index.js
Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
Failed to parse source map from 'C:\project\node_modules\schema-typed\src\locales\index.ts' file: Error: ENOENT: no such file or directory, open 'C:\project\node_modules\schema-typed\s
rc\locales\index.ts'

WARNING in ./node_modules/schema-typed/es/utils/basicEmptyCheck.js
Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
Failed to parse source map from 'C:\project\node_modules\schema-typed\src\utils\basicEmptyCheck.ts' file: Error: ENOENT: no such file or directory, open 'C:\project\node_modules\schema
-typed\src\utils\basicEmptyCheck.ts'

WARNING in ./node_modules/schema-typed/es/utils/checkRequired.js
Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
Failed to parse source map from 'C:\project\node_modules\schema-typed\src\utils\checkRequired.ts' file: Error: ENOENT: no such file or directory, open 'C:\project\node_modules\schema-t
yped\src\utils\checkRequired.ts'

WARNING in ./node_modules/schema-typed/es/utils/createValidator.js
Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
Failed to parse source map from 'C:\project\node_modules\schema-typed\src\utils\createValidator.ts' file: Error: ENOENT: no such file or directory, open 'C:\project\node_modules\schema
-typed\src\utils\createValidator.ts'

WARNING in ./node_modules/schema-typed/es/utils/createValidatorAsync.js
Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
Failed to parse source map from 'C:\project\node_modules\schema-typed\src\utils\createValidatorAsync.ts' file: Error: ENOENT: no such file or directory, open 'C:\project\node_modules\s
chema-typed\src\utils\createValidatorAsync.ts'

WARNING in ./node_modules/schema-typed/es/utils/formatErrorMessage.js
Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
Failed to parse source map from 'C:\project\node_modules\schema-typed\src\utils\formatErrorMessage.ts' file: Error: ENOENT: no such file or directory, open 'C:\project\node_modules\sch
ema-typed\src\utils\formatErrorMessage.ts'

WARNING in ./node_modules/schema-typed/es/utils/index.js
Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
Failed to parse source map from 'C:\project\node_modules\schema-typed\src\utils\index.ts' file: Error: ENOENT: no such file or directory, open 'C:\project\node_modules\schema-typed\src
\utils\index.ts'

WARNING in ./node_modules/schema-typed/es/utils/isEmpty.js
Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
Failed to parse source map from 'C:\project\node_modules\schema-typed\src\utils\isEmpty.ts' file: Error: ENOENT: no such file or directory, open 'C:\project\node_modules\schema-typed\s
rc\utils\isEmpty.ts'

webpack compiled with 18 warnings
[...]

Expected Behavior

No warnings.

Typescript types declaration.

As this becomes as an standard, and allows wider adoption, it is worth to add to library the typescript types declaration.

addRule 未触发。

StringType().isRequired('This field is required.').addRule(()=>({
     hasError:false,
    errorMessage:'No Error'
  })).addRule(()=>({
     hasError:true,
    errorMessage:'Error!!'
  }))
})

第二个 addRule 未执行。
版本 1.2.1

Suggest add validateOnBlur,validateOnChange and hasError property to the Type and errors

validateOnBlur,validateOnChange it's very usable to describe the schema of the form for the special use, for some case, i build a reack hook form for material. and errors property hasError is very useful for disable the button
eg:
type.js:

class Type {
  constructor(name) {
    this.name = name;
    this.required = false;
    this.requiredMessage = '';
    this.trim = false;
    this.rules = [];
    this.priorityRules = []; // Priority check rule
+    this.validateOnBlur = false;
+   this.validateOnChange = false;
  }
....

+ checkOnChange(bool = true) {
    this.validateOnBlur = typeof bool === 'boolean'? bool: false;
    return this;
  }
+ checkOnBlur(bool = true) {
    this.validateOnChange = typeof bool === 'boolean'? bool: false;
    return this;
  }
}

schema.js:

 check(data) {
+    const checkResult = { hasError:false };
    Object.keys(this.schema).forEach(key => {
      checkResult[key] = this.checkForField(key, data[key], data);
+      checkResult.hasError === false && (checkResult.hasError = checkResult[keys[i]].hasError);
    });
    return checkResult;
  }
checkAsync(data) {
+    const checkResult = { hasError:false };
    const promises = [];
    const keys = [];

    Object.keys(this.schema).forEach(key => {
      keys.push(key);
      promises.push(this.checkForFieldAsync(key, data[key], data));
    });

    return Promise.all(promises).then(values => {
      for (let i = 0; i < values.length; i += 1) {
        checkResult[keys[i]] = values[i];
+        checkResult.hasError === false && (checkResult.hasError = checkResult[keys[i]].hasError);
      }
      return checkResult;
    });
  }

Add className and ref props for table component

What problem does this feature solve?

When we try to access the outermost tag, there is no other way but to use the parent element.

What does the proposed API look like?

It will be useful if we can have ref and className for this component.
For example, to add animation to the table, we need ref.

StringType().isRequired() triggering error with empty string

As explained in title. StringType().isRequired() triggering error with empty string.

Example data:

{
  val: ""
}

Schema:

 SchemaModel ({
  val: StringType().isRequired() 
})

Expected behavior:

{ val: { hasError: false } }

Current behavior:

{ val: { hasError: true, errorMessage: undefined } }

`addRule` Promise issue

What version of schema-typed are you using?

2.0.3

Describe the Bug

The typescript type for MixedModel.addRule does not allow for promises to be returned from the onValid callback. It is not just a typing issue, as it is an API issue. The rules have no way of knowing if a function is async, until they are executed, because of this rules are entirely dependent on being called by the correct validator.

export type ValidCallbackType<V, D, E> = (
  value: V,
  data?: D,
  filedName?: string | string[]
) => CheckResult<E> | boolean;
...
export interface RuleType<V, D, E> {
  onValid: ValidCallbackType<V, D, E>;

Expected Behavior

The types would allow promises to be returned from the onValid function.

To Reproduce

The following from the documentation does not work in typescript.

const model = SchemaModel({
  username: StringType()
    .isRequired('This field required')
    .addRule((value:string):Promise<boolean> => {
      return new Promise(resolve => setTimeout(resolve, 500, value === 'abc'));
    }, 'Username already exists'),
});

I imagine the real fix is to add addAsyncRule method that accepts promise return types. This would of course be a breaking change.

The other 'fix' is to keep its existing api, and just ignore the async result when a validation that is async is called by the non-async validator. Something like:

export type ValidCallbackType<V, D, E> = (
  value: V,
  data?: D,
  filedName?: string | string[]
) => CheckResult<E> | boolean | Promise<boolean | CheckResult<E>>;

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.