且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何验证仅通过JavaScript正则表达式输入的字母和空格

更新时间:2023-02-21 11:16:07

你可以使用javascript test()验证名称字段的方法。 test()方法测试字符串中的匹配。

  /^[A-Za-z\s]+$/.test(x)//如果匹配则返回true,为az和AZ和空格vaidates 

  / ^ [A-Za-z] + $ /.test(x)


I have an input type="text" for names in my HTML code. I need to make sure that it is a string with letters from 'a' to 'z' and 'A' to 'Z' only, along with space(s).

This is my HTML code:

<form action="" name="f" onsubmit="return f1()">
                Name : <input type="text" name="name">

I'm expecting my JavaScript to be something like this:

function f1() 
{  
   var x=document.f.name.value;  
   ..... 
   ..... 
   return false;
}

PS: I'm not really familiar with Regular Expressions, so please do put up an explanation with the code.

You can use javascript test() method to validate name field. The test() method tests for a match in a string.

/^[A-Za-z\s]+$/.test(x) //returns true if matched, vaidates for a-z and A-Z and white space

or

/^[A-Za-z ]+$/.test(x)