0

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-9\s-_]+"
        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-9\s]+". 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 2

1

The issue is in pattern [A-Za-z0-9\s-_]+. 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-9\s_-]+"

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).

0

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

1

Not the answer you're looking for? Browse other questions tagged or ask your own question.