I am using React with Formik & Yup , currently I have a input field which is as f
<input
type="fname"
name="fname"
onChange={handleChange}
onBlur={handleBlur}
value={values.fname}
className="form-control inp_text"
id="fname"
/>
I have the Yup logic as
fname: Yup.string()
.required("First Name is a required field")
.min(1, "Name is too Short")
.max(20, "Name is too Big")
.matches(
/^[A-Z][A-Za-z]*( [A-Z][A-Za-z]*)*$/,
"Not a correct format. Eg. Rahul Kumar "
),
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
CodePudding user response:
You can convert the value to Camel Case before calling handleChange
like:
const handleChangeWithCamelize = (e) => {
const copyE = { ...e };
copyE.target.value = camelize(copyE.target.value);
handleChange(e);
};
<input
id="fname"
type="text"
value={values.fname}
onChange={handleChangeWithCamelize}
onBlur={handleBlur}
className={
errors.fname && touched.fname
? "text-input error"
: "text-input"
}
/>
and camel case converter function will be like:
function camelize(text) {
const words = text.split(" ");
for (let i = 0; i < words.length; i ) {
if (words[i] && words[i].length > 0) {
words[i] = words[i][0].toUpperCase() words[i].substr(1);
}
}
return words.join(" ");
}
You can take a look at this sandbox for a live working example.
CodePudding user response:
The camelize
function @Ahmet Emre Kılınç posted can be simplified with a single regex:
function camelize(text) {
return text.replace(/\b[a-z]/g, m => m.toUpperCase());
}