htmlregexformsregression

Need Regex Pattern for a form fieldin proper name


I want to create a HTML pattern for a field as (Display name). There isn't any more complex file, just a HTML file with one field.

The requirements are:

  1. The starting character of the field can just be a uppercase letter and following letters should be lowercase but can be any kind of characters (number, special character)
  2. Can't start with space and can't use consecutive spaces
  3. Words after space can start with (letter, number, special character) but if its a letter should be uppercase

I could write the regex expression that match the most of the requirements but special characters aren't being included.

^[A-Z][a-z]*( [A-Z][a-z]*)*$

but I want to use special characters and numbers anywhere (except the first letter) and problem is happening here, this is the pattern:

^[A-Z][a-z0-9@()\[\]{}._\-!#$%&'*+\/=?^`|~]*( [A-Z][a-z0-9@()\[\]{}._\-!#$%&'*+\/=?^`|~]*)*$

and I'm getting this error on console:

this causing this error: Unable to check <input pattern=‘^[A-Z][a-z0-9@()\[\]{}._\-!#$%&'*+\/=?^|~]*( [A-Z][a-z0-9@()\[\]{}._\-!#$%&'*+\/=?^|~]*)*$’> because ‘/^[A-Z][a-z0-9@()\[\]{}._\-!#$%&'*+\/=?^|~]*( [A-Z][a-z0-9@()\[\]{}._\-!#$%&'*+\/=?^|~]*)*$/v’ is not a valid regexp: invalid character in class in regular expression

I tried many other things, but using special characters is a troublemaker for me. Would you please tell me what's the correct pattern for it?

Thanks.

This is the whole code:

const registrationForm = document.querySelector('#registration-form');

registrationForm.onsubmit = e =>
  {
  e.preventDefault();  // 4 testing mode
  console.clear();
  console.log( ':) name  accepted ', registrationForm.display_name.value);
  }
<form id="registration-form">
  <!-- Display Name Field -->
  <label for="display-name">Display Name:</label>
  <input type="text" id="display-name" name="display_name" pattern="^[A-Z][a-z0-9@()[\]{}._\-!#$%&'*+/=?^`|~]*(( [A-Z][a-z0-9@()[\]{}._\-!#$%&'*+/=?^`|~]*)| (?! )[a-zA-Z0-9@()[\]{}._\-!#$%&'*+/=?^`|~]*)*$" title="Display name must start with a letter, have no consecutive spaces, and each word must start with an uppercase letter. Length must be between 2 and 50 characters."
    minlength="2" maxlength="50" required>
  <br><br>

  <button type="submit">Submit</button>
</form>


Solution

  • I tried other answers but all of them getting error on browser console, so i found the closest thing to what i wanted and without getting any error:

    ^[A-Z][a-zA-Z0-9~`\!@#\$%\^&\*\(\)_\+\-=\[\]\\\{\}\|;':\,\.\/<>\?]*( (?! )[a-zA-Z0-9~`\!@#\$%\^&\*\(\)_\+\-=\[\]\\\{\}\|;':\,\.\/<>\?]*)*$
    

    The only thing i exclude was "