验证输入全名



有一个任务:字段" First Name Last Name "只能包含2个单词(名和姓)。每个单词的最小长度为3个字符,最大长度为30个字符。字与字之间只有一个空格

问题是,在第一个单词之后,当你放一个空格时,它已经返回true。为什么?如何检查这个输入中的1 ?

const validateInput = (value) => {
const lengthValue = value.split(' ').length
if (lengthValue !== 2) {
return false
} else {
return value.split(' ').filter(el => el.length > 3 && el.length <= 30) ?
value.search(/[A-Za-z]+(s+[A-Za-z]+)?/gi) !== -1 ?
true :
false :
''
}
}

  • 在测试
  • 之前使用trim来删除单词周围的空格
  • 返回后不需要else。更容易阅读
  • 为什么要测试名称中的空格?这只在用户粘贴换行符或制表符时起作用,因为您在空格
  • 上进行了分割。
  • 你有一个嵌套的三元,为什么你会返回一个空字符串在那里?

还请阅读这篇文章,了解程序员相信的关于名称的谎言

const re = /[A-Za-z]{3,30}/;
const validateInput = (value) => {
const val = value.trim();
if (val === "") return false;
const arr =  value.split(' ');
if (arr.length != 2) return false;
const [firstName, lastName] = arr;
return re.test(firstName) && re.test(lastName); // we could use .every here but you only have two
}
console.log(validateInput("Hans Anders"));
console.log(validateInput("Prince"));
console.log(validateInput("X Æ A-12"));
console.log(validateInput("   A    "));

您可以检查是否有。

小于等于2且所有单词的长度在指定范围内。

const message = document.querySelector("small");
document.querySelector("input").addEventListener("keyup", (e) => {
const isValid = validateInput(e.target.value);
if (isValid) {
message.textContent = "Valid input";
} else {
message.textContent = "Invalid input";
}
});
const validateInput = (input) => {
const words = input.split(" ");
return words.length <= 2 && words.every((w) => /^[A-Za-z]{3,30}$/.test(w));
};
<div>
<label>
Name:
<input type="text" />
</label>
</div>
<small>Invalid input</small>

最新更新