Conditional Error Handling on MUI controls in react hook form - reactjs

I want to make field mandatory on the base of condition. Here is my code snippet
<Controller
name={"InvoicingAddress.address_line_1"}
control={control}
rules ={{
required: "This field is required"
}}
render={({ field: { onChange, value },
}) => (
<Input
theme={theme}
fullWidth={true}
label={"Address Line 1"}
placeholder="House number, street name"
type="text"
onChange={onChange}
value={value}
error={errors?.InvoicingAddress?.address_line_1?.message}
></Input>
)}
/>
I want to make required on the basis of condition:
something like this:
{condition &&
rules ={{
required: "This field is required"
}}
}
but the above code is not working

After a lot of research, I've solved something like this
const [applyValidation, setApplyValidation] = useState<boolean>(false);
function setError(): boolean {
if(got error depending upon your condition)
return true;
else
return false;
}
<Controller
name={"OfficeAddress.City"}
control={control}
rules={{
required: {
value: applyValidation,
message: ValidationMessages.CITY_REQUIRED
}
}}
render={({ field: { onChange, value } }) => (
<Input
theme={theme}
fullWidth={true}
label={"City"}
placeholder="e.g. company, apartment, building..."
type="text"
onChange={(e) => {
onChange(e)
setApplyValidation(setError());
}}
value={value}
error={errors?.OfficeAddress?.City?.message}
></Input>
)}
/>

Related

React hooks form doesn't accept files, but string to system path instead

I'm trying to load a file using React hooks form and yup, but by wrapping the input type file component in Controller I get instead of the usual Blob, system paths like value
Example of result:
C:\\fakepath\\image.jpeg
Expected result
Blob file
Code example:
Link to sandbox: https://codesandbox.io/s/react-select-with-react-hook-form-forked-4t6ncr?file=/src/App.js
Code:
<form onSubmit={handleSubmit(saveData)}>
{!countryValue && (
<Controller
name="country"
control={control}
render={({ onChange, value, ref }) => (
<Select
options={country}
value={country.find((c) => c.value === value)}
onChange={(val) => onChange(val.value)}
/>
)}
rules={{ required: true }}
/>
)}
{countryValue && (
<Controller
name="country"
control={control}
render={(field) => {
const { onChange } = field;
return <input {...field} type="file" onChange={onChange} />;
}}
rules={{ required: true }}
/>
)}
{errors.country && <div>Field is rquired</div>}
<button type="submit">Save</button>
</form>

How can I check if the value of the inputs is the same?

I have a form where two fields have to have the same value to be able to continue with the process, for this I have created a component that is in charge of the comparison, the problem is that it does not show me the value of the input to be able to make the comparison . this is my component.
const UIInput = ({ register, rules, name, errors, label, type, options, equals, getValues, ...props }) => {
return (
<div>
<label >{label}</label>
{type === 'select' ?
<select
{...(register && register(name, rules))}>
{options.map(o => (
<option key={o}>{o}</option>
))}
</select>
:
<input
name={name}
{...props}
placeholder={label}
/* {...(register && register(name, rules))} */
{...(register && register({validate:{
name:value=>(value === getValues().email) || console.log('are not the same')
}}))}
/>
/* register && register(name, rules)) */
}
{errors[name] && <ErrorMessaje>{errors[name]?.message}</ErrorMessaje>}
</div>
)
}
export default UIInput
And this is how I use it:
<UIInput
name="email"
register={register}
errors={errors}
label="Email"
defaultValue={dataForm.email}
type="email"
rules={{ required: 'Enter an email' }}
/>
<UIInput
name="email2"
register={register}
errors={errors}
label="Confirmar Email"
type="email"
rules={{ required: 'Has to be the same value' }}
getValues={getValues}
/>
when I run the code the error it sends me is "path.split is not a function"

Validating radio button with React Hook Form

I have a custom radio button component in React looking like this:
export default function SingleSelectionButton(props) {
const {
values, name, required, errors, defaultData,
xs, md, register, infoBox, infoBoxContent, validateField } = props;
return (
<>
<Form.Group>
<Form.Label>
<FormattedMessage
id={name}
/>
</Form.Label>
{values.map((value) => (
<span key={value} className="SingleSelectionButton">
<input
{...register(name, { required: required}
id={name + value}
type="radio"
name={name}
value={value}
defaultChecked={defaultData.primary[name] === value}
/>
<label htmlFor={name + value}>
<FormattedMessage id={value} />
</label>
</span>
))}
</Form.Group>
</>
);
};
I call it like this, using an array for the different values:
<SingleSelectionButton
name="us_person"
md={6}
values={["yes", "no"]}
register={register}
required={true}
errors={errors}
validateField="no"
/>
The validation with required is working fine.
The problem is that I don't manage to validate a value in particular.
I have tried the following:
<input
{...register(name, { required: required, validate: value => value === validateField })}
id={name + value}
type="radio"
name={name}
value={value}
defaultChecked={defaultData.primary[name] === value}
/>
And also:
<input
{...register(name, { required: required, pattern: validateField })}
id={name + value}
type="radio"
name={name}
value={value}
defaultChecked={defaultData.primary[name] === value}
/>
So far no joy. What am I missing?

How to exclude special characters from a Textfield in React Hooks Form 7.0

<Controller
control={control}
name="txnId"
render={({ field }) => (
<MuiTextField
type="text"
required
id="txnId"
label="Payment Ref. No."
variant="outlined"
InputLabelProps={{
shrink: true,
}}
{...field}
/>
)}
/>
My useForm looks like this where I am setting the txnId. MuiTextField is the Material UI Textfields here
const { control, setValue, getValues} = useFormContext();
const methods = useForm({
defaultValues: {
txnId:""
}
});
I'm not sure but maybe it's be better to use controlled input instead od uncontrolled one like below:
const [state,setState] = useState({
txnId:""
});
and then use onchange to set value
const onChange = (e)=>{
const {value,name}=e.target;
//some logic to exclue char before setting in state
setState(s=>({...s,txnId:vakue});
}
<Controller
control={control}
name="txnId"
render={({ field }) => (
<MuiTextField
type="text"
required
id="txnId"
label="Payment Ref. No."
variant="outlined"
value={state.txnId}
onChange={onChange}
InputLabelProps={{
shrink: true,
}}
{...field}
/>
)}
/>

React Hook Form problem with validating using validate function

Hey I'm currently working on validation using customized Antd inputs and React Hook Form.
Currently I have problem with validating fields for URLs (single url and image one) with regex.
I've checked both of regex and they are working
Generally I can't submit the form with correct data, the problem happens within the validation using regex
The form part
<Controller
as={
<InputField
label="URL"
name="url"
placeholder="Enter URL"
error={errors.url}
errorText="URL Error"
/>
}
control={control}
type="text"
name="url"
defaultValue=""
rules={{
validate: (value) => {
return INPUT.urlPattern.test(value);
}
}}
/>
<Controller
as={
<InputField
label="Image Url"
name="imageUrl"
placeholder="enter ImageURL"
error={errors.imageUrl}
errorText="Error on imageUrl"
/>
}
control={control}
type="text"
name="imageUrl"
defaultValue=""
rules={{
validate: (value) => {
return INPUT.imageURLPattern.test(value);
}
}}
/>
Custom antd input component render function
return (
<>
<label className="label" htmlFor={name}>
{label}
</label>
<Styled.Input
placeholder={placeholder}
maxLength={maxLength}
value={value}
onChange={handleInputCounter}
{...(counter
? {
suffix: (
<Styled.WordCounter>
{counterValue} / {maxLength}
</Styled.WordCounter>
)
}
: {})}
/>
{error && <p className="error">{errorText}</p>}
</>
);
I've prepared little demo on codesandbox
https://codesandbox.io/s/react-hook-form-validate-antd-gyhnh?file=/src/EntryForm.tsx

Resources