How to use textbox with characters and numbers only in vuejs?

Viewed 916

 methods: {      
      isEmail(e) {
       let char = String.fromCharCode(e.keyCode); // Get the character
       if(/^[A-Za-z]+$/.test(char)) return true; // Match with regex 
       else e.preventDefault(); // If not match, don't add to input text 
                   },
 <input type="email" v-model.trim="$v.email.$model" :class="{'is-invalid': validationStatus($v.email)}" class="input-section" placeholder="Enter your company email ID" :maxlength="maxemail" v-on:keypress="isEmail($event)"> 

<div v-if="!$v.email.required" class="invalid-feedback">The email field is required. 
</div>
<div v-if="!$v.email.maxLength" class="invalid-feedback">30 characters {{ 
$v.email.$params.maxLength.min }} only</div>

My issue is that at present the textbox above is only accepting characters (A to Z and z to A). However, I need it to accept alpha numeric characters (i.e A to Z, a to z, 0 to 9 and special characters like *,&,@). How do I change the code above to accomplish this?

1 Answers

As you may or may not know, /^[A-Za-z]+$/ is a regular expression and is currently limited to only allow the values A to Z and a to z.

If I were to purely answer your question, it would be to add the missing characters to your existing regular expression. E.g. /^[A-Za-z0-9*&@]+$/

Note that there are online tools you can use to test and validate your regular expressions.
For example: https://regex101.com/r/uE4GfO/2

However, currently it's only validating character per character, while it would be more efficient (and most likely more correct) to validate the entire string at once.

Additionally, it looks like you're trying to validate an email address. You should consider using a regular expression as discussed here: See How to validate an email address in JavaScript

Related