简体   繁体   English

使用Javascript正则表达式验证HTML表单

[英]Validating HTML form using Javascript regular expression

I am having a script which validates a user's name. 我有一个验证用户名的脚本。 When the user enters name without spaces then it works fine. 当用户输入不带空格的名称时,它将正常工作。 If user enters name with spaces (name, surname, lastname etc) then it is not working. 如果用户输入的名称带有空格(名称,姓氏,姓氏等),则它不起作用。 I am trying to capture 'space' character using \\s but it is not working. 我正在尝试使用\\s捕获“空格”字符,但是它不起作用。

My script is: 我的脚本是:

var name=document.forms["newform"]["fullname"].value; //get the name from HTML form
var charpos = name.search("[^A-Za-z\s]");
if (name.length <= 0 || name.length>=50 || charpos >= 0)
{
    alert('wrong.');
}
else
{
     alert('correct');
}

Input1: AFGH 输入1: AFGH

Output1: correct 输出1: 正确

Input2: ABCD EFGH 输入2: ABCD EFGH

Output2: wrong 输出2: 错误

When Input2 is given, charpos gets the value '5'. 给定charpos时, charpos的值为'5'。

The string literal is swallowing the \\ . 字符串文字正吞住\\

You should use a regex literal: 您应该使用正则表达式文字:

name.search(/[^A-Za-z\s]/);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM