I am using React with Formik & Yup , currently I have a input field which is as f
JavaScript
x
10
10
1
<input
2
type="fname"
3
name="fname"
4
onChange={handleChange}
5
onBlur={handleBlur}
6
value={values.fname}
7
className="form-control inp_text"
8
id="fname"
9
/>
10
I have the Yup logic as
JavaScript
1
9
1
fname: Yup.string()
2
.required("First Name is a required field")
3
.min(1, "Name is too Short")
4
.max(20, "Name is too Big")
5
.matches(
6
/^[A-Z][A-Za-z]*( [A-Z][A-Za-z]*)*$/,
7
"Not a correct format. Eg. Rahul Kumar "
8
),
9
which is working when I manually write it but my requirement is that if I write at run time only it should covert to Camel case
for Example
abhimanu singh -> Abhimanu Singh Abhi Raj -> Abhi Raj
Like this can anyone help me or guide me
Advertisement
Answer
You can convert the value to Camel Case before calling handleChange
like:
JavaScript
1
19
19
1
const handleChangeWithCamelize = (e) => {
2
const copyE = { e };
3
copyE.target.value = camelize(copyE.target.value);
4
handleChange(e);
5
};
6
7
<input
8
id="fname"
9
type="text"
10
value={values.fname}
11
onChange={handleChangeWithCamelize}
12
onBlur={handleBlur}
13
className={
14
errors.fname && touched.fname
15
? "text-input error"
16
: "text-input"
17
}
18
/>
19
and camel case converter function will be like:
JavaScript
1
12
12
1
function camelize(text) {
2
const words = text.split(" ");
3
4
for (let i = 0; i < words.length; i++) {
5
if (words[i] && words[i].length > 0) {
6
words[i] = words[i][0].toUpperCase() + words[i].substr(1);
7
}
8
}
9
10
return words.join(" ");
11
}
12
You can take a look at this sandbox for a live working example.