skip to Main Content

I have a simple form in my Vue 3 app as below,

<form @submit.prevent="createProject">
<div class="my-3">
    <label for="name" class="form-label">Project Name</label>
    <input
        type="text"
        class="form-control"
        id="name"
        placeholder="Enter project name"
        v-model="projectName"
        pattern="[A-Za-z0-9s-_]+"
        required
    />
</div>
<div class="text-end mt-4">
    <button class="btn btn-dark" type="submit">Save</button>
</div>

Pattern validation is working when pattern="[A-Za-z0-9s]+". But when dash & underscore are added, pattern validation is not working and allow to submit.

Could someone explain the logic behind this behavior?

2

Answers


  1. You have to mention all the special character or dashes or underscore in different brackets

    Login or Signup to reply.
  2. The issue is in pattern [A-Za-z0-9s-_]+. In your pattern, the dash is between "s" and "_", which lead to unexpected behavior because the dash is being interpreted as a range between the whitespace character class (s) and the underscore (_).

    if you want to use dash and pattern in your input you have include then in your pattern should be,

    pattern="[A-Za-z0-9s_-]+"
    

    and simple explanation for the pattern is,

    • "A-Za-z" matches any uppercase or lowercase letter.

    • "0-9" matches any
      digit.

    • "s" matches any whitespace character (spaces, tabs, line
      breaks).

    • "_" matches the underscore character.

    • "-" matches the dash character, placed at the end to avoid it being interpreted as a range.

    we can understand more about these pattern through Regex ( Regular expressions).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search