Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

validate nested this.state #36

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 23 additions & 8 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,22 +35,37 @@ export default class ValidationComponent extends Component {
// Reset errors
this._resetErrors();
// Iterate over inner state
for (const key of Object.keys(this.state)) {
// Check if child name is equals to fields array set up in parameters
const rules = fields[key];
if (rules) {
// Check rule for current field
this._checkRules(key, rules, this.state[key]);
}
};
this.validateObject(fields, this.state)
return this.isFormValid();
}

validateObject(fields, object, parentFieldName) {
if(object == null || object==='undefined') return;

for (const key of Object.keys(object)) {
if(typeof object[key] === 'object' && !Array.isArray(object[key]) && fields[key]){
this.validateObject(fields[key], object[key], key)
}
else{
// Check if child name is equals to fields array set up in parameters
const rules = fields[key];
if (rules) {
// Check rule for current field
if(parentFieldName == null || parentFieldName==='undefined')
this._checkRules(key, rules, object[key]);
else
this._checkRules(parentFieldName + "." + key, rules, object[key]);
}
}
}
}

// Method to check rules on a spefific field
_checkRules(fieldName, rules, value) {
if (!value && !rules.required ) {
return; // if value is empty AND its not required by the rules, no need to check any other rules
}

for (const key of Object.keys(rules)) {
const isRuleFn = (typeof this.rules[key] == "function");
const isRegExp = (this.rules[key] instanceof RegExp);
Expand Down