Form input javascript

Im trying to make a simple form and want a number input for swedish social security ID
The format is YYYYMMDDXXXX

So max lenght 12 and min length 12.

 <input type="number" min="0" pattern="\d{11}" oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);"
    maxlength = "12" placeholder="Personnummer" name="frmPID" value="<? echo $rowFName; ?>" required>

The HTML code you provided is a good start, but it has a couple of issues:

  1. type="number" is not suitable for inputting a social security ID because the ID contains letters as well as numbers.
  2. The pattern attribute is not necessary since it’s not being used correctly. The pattern you’re looking for contains letters and numbers in a specific format, so a regular expression would be more appropriate.

Here’s an updated HTML code that should work for your needs:

<input type="text" pattern="^(19|20)\d{6}-\d{4}$" placeholder="YYYYMMDDXXXX" name="frmPID" value="<? echo $rowFName; ?>" required>

Explanation:

  • type="text" is used instead of type="number" since we need to allow letters in the input.
  • pattern="^(19|20)\d{6}-\d{4}$" is a regular expression that matches the format you specified: YYYYMMDDXXXX. It allows for years starting with either 19 or 20, followed by 6 digits for the date, and ending with 4 digits for the ID number.
  • placeholder="YYYYMMDDXXXX" provides a hint to the user about the required format.
  • required makes the input field required so the user cannot submit the form without entering a valid social security ID.

Note: If you prefer to use a maxlength attribute instead of a regular expression, you can use maxlength="12" instead of pattern="^(19|20)\d{6}-\d{4}$". However, keep in mind that this won’t validate the format of the input, only the length.

Best regards

Sponsor our Newsletter | Privacy Policy | Terms of Service