reactjs-forms is a React package that contains a few React components and hook system. The components are almost the same as React syntactic form elements.So you may use all attributes which you can use them on syntactic form elements.
Extended Features
reactjs-forms contains Input,Select and Textarea components.that components have validation,customValidation,identity props.Validation prop is a PrimaryValidateObject typed object prop.Validation accepts an object which contains primary validations.(buit-in validations).CustomValidation accepts a function is that returns object.That object has msg and result props.Msg is used to send a msg to ValidationResultObject whenever custom validation result is false.
Primary Validations
descriptor
is value forced
explanation
required
No
value cannot be empty or undefined
isEmail
No
value must be email address format
isAlpha
No
value must contain letters
isUnicode
No
value must contain unicode letters
isName
No
value must be name format
isNumeric
No
value can be numbers
isAlphaNumeric
No
value must contain letters and numbers
isUnicodeNumeric
No
value must contain unicode letters and numbers
maxLen
Yes
value must contain fewer characters than {{value}}
minLen
Yes
value must contain more characters than {{value}}
max
Yes
value must be numeric that lower than {{value}}
min
Yes
value must be numeric that greater than {{value}}
Primary validations are under development.You can help me to declare new features so you can be collaborator.Additionally you can access primary validation list under core/pipelines.ts
Custom Validations
You may declare custom validations.Custom validations accpet function with 2 parameters value and identity and returns an object that has result and msg props.
we have given an example see Example – 2
Extended Form Element and Multiple Select Element
Form element has validation results in submit handler via e.currentTarget.validation
Primitive React Syntactic select elements cannot set values as array.You have to make an effort to get all selected options from HTMLSelectAttibutes but you don’t need it when using reactjs-forms Select Component.So you can access all selected option values via e.target.values see Example – 2
Examples
we have to wrap React compoents with FormValidation Component that contains base context provider
import {useMemo,useState}from"react";import{Form,Input,Textarea,useFormValidation}from"reactjs-forms";constApp=()=>{const[email,setEmail]=useState("");const[name,setName]=useState("");const[age,setAge]=useState("");const[address,setAddress]=useState("");const[errors,setErrors]=useState({});const[addressErrors,setAddressErrors]=useState({});constvalidation=useFormValidation();constemailErrors=useMemo(()=>errors.email ? errors.email.map((v,i)=><likey={i}>{v.msg}</li>) : [],[errors]);constnameErrors=useMemo(()=>errors.name ? errors.name.map((v,i)=><likey={i}>{v.msg}</li>) : [],[errors]);constageErrors=useMemo(()=>errors.age ? errors.age.map((v,i)=><likey={i}>{v.msg}</li>) : [],[errors]);constonlyAddressErrors=useMemo(()=>addressErrors.address
? addressErrors.address.map((v,i)=><likey={i}>{v.msg}</li>)
: [],[addressErrors]);return(<div><FormonSubmit={(e)=>{e.preventDefault();console.log(e.currentTarget.validation);//we have accessed to the validation results via submit event currentTargetsetErrors(validation().result);//get validation errors and set errors state for rendering}}><labelhtmlFor="email">Email:</label><InputonChange={(e)=>setEmail(e.target.value)}value={email}//we have to declare value attributeidentity="email"//also we have to declare identity attribute because of that value is used to get validation resultsid="email"//type="email"validation={{required: true,isEmail: true,}}/>{/* list all email erros*/}<ul>{emailErrors}</ul><br/><labelhtmlFor="name">Name:</label><InputonChange={(e)=>setName(e.target.value)}value={name}identity="name"id="name"validation={{isName: {msg: "custom message",//you may or not declare a custom messagevalue: true,//you dont have to declare value also},}}/>{/* list all name erros*/}<ul>{nameErrors}</ul><br/><labelhtmlFor="age">Age:</label><InputonChange={(e)=>setAge(e.target.value)}value={age}identity="age"id="age"validation={{isNumeric: true,min: 17,//you can assign value or msg like object notationmax: {value: "120",msg: "What was that.holy lighten!!!!!",},}}/><ul>{ageErrors}</ul><br/><labelhtmlFor="address">Address:</label><br/><TextareaonChange={(e)=>setAddress(e.target.value)}value={address}identity="address"id="address"validation={{required: true,isUnicode: true,}}onBlur={()=>{setAddressErrors(validation("address").result);//you may send args to get only specific inputs errors like ["adress","email"] or "address","email"}}/><ul>{onlyAddressErrors}</ul><button>Send</button></Form></div>);};exportdefaultApp;
Example – 2
In this example we will create a custom validator and also we will use a select form element with multiple selected attribute
import {useMemo,useState}from"react";import{Form,Input,Select,useFormValidation}from"reactjs-forms";constOther=()=>{const[password,setPassword]=useState("");const[passwordRepeat,setPasswordRepeat]=useState("");const[jobs,setJobs]=useState([]);const[errors,setErrors]=useState({});constvalidation=useFormValidation();constpasswordErrors=useMemo(()=>errors.password
? errors.password.map((v,i)=><likey={i}>{v.msg}</li>)
: [],[errors]);constpasswordRepeatErrors=useMemo(()=>errors.passwordRepeat
? errors.passwordRepeat.map((v,i)=><likey={i}>{v.msg}</li>)
: [],[errors]);constjobsErrors=useMemo(()=>errors.jobs ? errors.jobs.map((v,i)=><likey={i}>{v.msg}</li>) : [],[errors]);//we have created a custom validator functionfunctionisEqulPasswords(password){returnfunction(value,identity){return{msg: "passwords dont match",result: password===value,};};}return(<div><FormonSubmit={(e)=>{e.preventDefault();setErrors(validation().result);}}><labelhtmlFor="password">Password:</label><InputonChange={(e)=>setPassword(e.target.value)}value={password}type="password"identity="password"id="password"validation={{required: true,}}/><br/><ul>{passwordErrors}</ul><labelhtmlFor="password-repeat">Password-Repeat:</label><InputonChange={(e)=>setPasswordRepeat(e.target.value)}value={passwordRepeat}type="password"identity="passwordRepeat"id="passwordRepeat"validation={{required: true,}}customValidation={{isEqulPasswords: isEqulPasswords(password),}}/><br/><ul>{passwordRepeatErrors}</ul><labelhtmlFor="name">Job:</label><SelectonChange={(e)=>{setJobs(e.target.values);//we have accessed directly all the selected values and we have set jobs state}}identity="jobs"multiplevalue={jobs}validation={{isAlpha: true,}}><optionvalue="1">Fornt-end Developer</option><optionvalue="2">Back-end Developer</option><optionvalue="3">Pixel Artist</option><optionvalue="4">UX Designer</option></Select><ul>{jobsErrors}</ul><button>Send</button></Form></div>);};exportdefaultOther;
Initialization With Custom Messages
If you wish you can also send a config props to the FormValidation component while wrap your components with it.
So we can change FormValidation component like this;
import Reactfrom"react";importReactDOMfrom"react-dom";importAppfrom"./App";importFormValidationfrom"reactjs-forms";constconfig={customMessages:{max:"{{identity}} can be maximum {{value}}",isEmai:"this email adress is invalid"
:
}}ReactDOM.render(<FormValidationconfig={config}><App/></FormValidation>,document.getElementById("root"));
in this “{{identity}} can be maximum {{value}}” string expression; {{identity}} is your identity prop of Input,Textarea or Select components.
{{value}} is value that in validation prop of Input,Textarea or Select components.
<InputonChange={(e)=>setCost(e.target.value)}value={cost}identity="cost"validation={{max: 1000,// in this example {{value}} represents number 1000}}/>
So “{{identity}} can be maximum {{value}}” will be “cost can be maximum 1000”
Custom Message Priorities
Ofcourse custom messages has a priority while processing.
So custom message priority;
Form Element Component’s validaiton msg props that you are declarated in components,
FormValidation Config’s msg props,
Default msg props
in this list 1 has highest priority and 3 has lowest priority.