Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make it so a string has to start with a capital letter with JavaScript?

Tags:

javascript

      <form action="http://www.cknuckles.com/cgi/echo.cgi" method="get" name="logOn">
              User Name:<br />
          <input type="text" name="userName" size="25" /><br />
              Password:<br />
          <input type="password" name="pw" size="25" /><br />

          <input type="submit" value="Log In" onClick="validate()"/> 
      </form>

Thats my HTML, I have figured out how to only get alpha numerical data into the fields, but how do I get it to only allow a User Name that starts with a capital?

      <script language="javascript">

              </script> 
like image 467
Jason Avatar asked Jun 06 '11 18:06

Jason


People also ask

How do you capitalize strings in JavaScript?

The toUpperCase() method converts a string to uppercase letters. The toUpperCase() method does not change the original string.

Can a JavaScript variable start with a capital letter?

Naming Convention for Variables JavaScript variable names are case-sensitive. Lowercase and uppercase letters are distinct. For example, you can define three unique variables to store a dog name, as follows. However, the most recommended way to declare JavaScript variables is with camel case variable names.

How do I make the first letter of a string lowercase in JavaScript?

The toLowerCase method converts a string to lowercase letters. The toLowerCase() method doesn't take in any parameters. Strings in JavaScript are immutable. The toLowerCase() method converts the string specified into a new one that consists of only lowercase letters and returns that value.

How do you Capitalise a string?

The simplest way to capitalize the first letter of a string in Java is by using the String. substring() method: String str = "hello world!"; // capitalize first letter String output = str. substring(0, 1).


1 Answers

The simplest way to check this is with a regular expression:

function(str){
    return /^[A-Z]/.test(str);
}

returns true when the input string starts with a capital, false otherwise. (This particular regular expression - the bits between the // characters - is saying, 'match the start of the string followed by any single character in the range A-Z'.)

In terms of your HTML above, we'll need the contents of the validate() function to determine where the regex match needs to go.

like image 71
Dan Davies Brackett Avatar answered Oct 28 '22 15:10

Dan Davies Brackett