From f74a711ff24c1e1b46404ab6083eff5873a2b9dc Mon Sep 17 00:00:00 2001 From: Stuart Yamartino Date: Tue, 25 Jul 2017 16:01:20 -0400 Subject: [PATCH] custom rules readme example --- README.md | 40 ++++++++++++++++++++++++++++++++++- src/simple-react-validator.js | 2 +- 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 2334abb..3229512 100644 --- a/README.md +++ b/README.md @@ -45,7 +45,7 @@ constructor() { - **Optional Class Name**: The class applied to the div that wraps the message, default is 'validation-message'. - **Optional Custom Error Messages**: Will override the normal error messages. -```javascript +```jsx render: function() { return (
@@ -111,3 +111,41 @@ This is the list of all the rules you can validate form inputs against. When usi |phone | | Must be a valid phone number. | |required | | Must be present, use with other rules to require them. | |url | | Must be a valid url. | + +## Custom Rules +You can write custom rules that you can use the validate. A rule is comprised of 3 parts; the name, the message, and the rule itself. Here is an example of adding a custom rule on initialize of the validator. + +Example: + +```javascript +constructor() { + this.validator = new SimpleReactValidator({ + 'ip' : { + message: 'The :attribute must be a valid IP address.', + rule: function(val, options)){ + // check that it is a valid IP address and is not blacklisted + this._testRegex(val,/^(?!0)(?!.*\.$)((1?\d?\d|25[0-5]|2[0-4]\d)(\.|$)){4}$/i) && options.indexOf(val) === -1 + } + } + }); +} +``` + +Usage: + +```jsx +render: function() { + return ( +
+

Give Me Your IP

+
+ + + {/* This is where the magic happens */} + {this.validator.message('ip_address', this.state.ip, 'required|ip')} +
+ ... +
+ ); +}, +``` diff --git a/src/simple-react-validator.js b/src/simple-react-validator.js index 4875239..48d11a6 100644 --- a/src/simple-react-validator.js +++ b/src/simple-react-validator.js @@ -45,7 +45,7 @@ class SimpleReactValidator{ return true; } - // if a message is present, show an error message + // if a message is present, generate a validation error react element customMessage(message, customClass){ if( message && this.messagesShown){ return this._reactErrorElement(message, customClass);