ReactJS Props Validation


If we need immutable data in our component, we can simply add props to reactDOM.render() function in main.js and use them within our component.

Validation of properties is a valuable way of forcing good use of the components. This will help to avoid potential bugs and problems during development, once the application is larger. It also makes the code more readable, since we can see how to use every variable.

Custom validators and collections

We can also use custom validation functions with PropTypes.arrayOf and PropTypes.objectOf. Used in this way, the custom validation function will be called for each key in the array or object.

Nevertheless, instead of three custom validation features will take five arguments. 
  1. propValue: The array of object itself
  2. key: The key of the current item in the iteration
  3.  componentName: The name of the component
  4.  location: The location of the validated data. It is usually “prop”
  5. propFullName: The fully resolved name of the current item being validated. For an array, this will be array[index]. For an object, this will be object.key
Here is a modified version of the isEmail custom validation function for use with collection types

1.const isEmail = function(propValue, key, componentName, location, propFullName) {
2.const regex = /^((([^<>()[]\.,;:s@"]+(.[^<>()[]\.,;:s@"]+)*)|(".+"))@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}])|(([a-zA-Z-0-9]+.)+[a-zA-Z]{2,})))?$/;
 
3.  if (!regex.test(propValue[key])) {
4.    return new Error(`Invalid prop `${propFullName}` passed to `${componentName}`. Expected a valid email address.`);
5.  }
6.}
7.
8.Component.propTypes = {
9. emails: PropTypes.arrayOf(isEmail)
10.}

All- purpose custom validators

All- purpose custom validators that can be used as standalone validators and also with collection types.

 1.const isEmail = function(propValue, key, componentName, location, propFullName) {
 2.  // Get the resolved prop name based on the validator usage
 3. const prop = (location && propFullName) ? propFullName : key;
 
 4. const regex = /^((([^<>()[]\.,;:s@"]+(.[^<>()[]\.,;:s@"]+)*)|(".+"))@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}])|(([a-zA-Z-0-9]+.)+[a-zA-Z]{2,})))?$/;
 
 5. if (!regex.test(propValue[key])) {
 6.  return new Error(`Invalid prop `${prop}` passed to `${componentName}`. Expected a valid email address.`);
 7.}
 8.}
 9.
10.Component.propTypes = {
11.email: PropTypes.oneOfType([
13. isEmail,
14.PropTypes.shape({
15.address: isEmail
16.})
17.]),
18. emails: PropTypes.arrayOf(isEmail)
19.}

Comments

Popular posts from this blog

Project

Closure Scope Chain

Microservices and Node.js