使用JavaScript进行输入验证
Input validation using JavaScript
我一直在尝试使用JavaScript创建一个验证,其中输入只能是字母和空格。每次我输入一个数字,它仍然会通过输入的数字。请查看下面的代码,并帮助我找出代码中的错误。
function validateForm()
{
var x=document.forms["form1"]["fname"].value;
if (x==null || x=="") {
alert("Enter Firstname");
return false;
}
else {
if (!x.value.match(/^[a-zA-Z ]+$/) && x.value != "") {
alert("You entered an invalid Firstname");
return false;
}
}
您的regexp应该表示类似的东西
/^[a-zA-Z's]+$/
空格有特殊字符(")-''s此外,中还有一个错误!x.value.match。您已经有x.的值
所以,你的全部功能应该是:
function validateForm() {
// get the edit and get its value
var edit = document.forms["form1"]["fname"].value;
// if there are no value in the edit, or
// there is only spaces and the string then return false
if (edit.trim() == "") {
alert("Enter your first name");
return;
}
// else if there is something, then let's check it
// this pattern allows any letter characters (both BIG and small)
// and spaces
// pay attention that the block inside this "if" will execute
// if no matches will found (e.x if there will digits in the input string)
// so it will works as we excepted
if (!edit.match(/^[a-zA-Z's]+$/g)) {
alert("Enter correct first name!");
return false;
}
// everything seems to be ok, return true
// alert('ok');
return true;
}
示例:http://cssdeck.com/labs/lagfrayg
相关文章:
- 是否有一种方法可以使用公共代码库在Java和JavaScript中进行输入验证
- 输入验证&使用javascript或asp返回
- 带有输入验证的Javascript
- 表单和输入验证
- 输入验证仅在lur上
- 使用jQuery进行输入验证
- 如何在 JavaScript 中将输入验证为数字
- 使用正则表达式进行输入验证
- Int 输入验证 - 解析服务器云代码
- jQuery/JS 输入验证
- 使用 Angular 要求输入启用注册:需要输入/验证
- 比较输入验证HTML JavaScript中的两个输入值
- simpleCart(js)将表单输入验证添加到电子邮件结账提交中
- Javascript:输入验证
- 淘汰计算和输入验证
- 使用javascript addevent监听器在引导程序html表单上输入验证
- 使用JavaScript进行输入验证
- HTML 5表单输入验证
- 禁用输入类型=数字的输入验证
- AngularJs表单中的输入验证