[英]Converting Input Tag to Camel Case at Runtime
I am using React with Formik & Yup, currently I have a input field which is as f我正在将 React 与 Formik & Yup 一起使用,目前我有一个输入字段为 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 abhimanu singh -> Abhimanu Singh Abhi Raj -> Abhi Raj
Like this can anyone help me or guide me像这样任何人都可以帮助我或指导我
You can convert the value to Camel Case before calling handleChange
like:您可以在调用
handleChange
之前将值转换为 Camel Case,例如:
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 会像:
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.您可以查看此沙盒以获取实时工作示例。
The camelize
function @Ahmet Emre Kılınç posted can be simplified with a single regex:发布的骆驼色
camelize
@Ahmet Emre Kılınç 可以使用单个正则表达式进行简化:
function camelize(text) {
return text.replace(/\b[a-z]/g, m => m.toUpperCase());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.