简体   繁体   中英

Tel field validation in html to allow digits and text but not @

This code is only digit allowed – Preference should be to allow to enter dash and/or brackets even text such as ext. but not an email address.

Can you please help me to edit this code? Very appreciated.

  <input type="text" maxlength="40" onkeypress="return event.charCode >= 48 && event.charCode <= 57" required name="phone" id="phonecontactselection">

You need a function to check only for @ character to avoid it, so:

function avoidEmailPartCharacter(event) {
  const code = event.keyCode || event.which;
  if (code === 64) {
    event.preventDefault();
  }
}

then you pass the function to the input keypress handler, like so:

<input type="type" keypress={avoidEmailPartCharacter(this)} />

it should do the trick

It's preferable to move such kind of logic of out template, into a dedicated function, however, in case you really have to make it inline , it's possible to match input character against a regex as follows:

 <input type="text" maxLength="40" onkeypress="return !!String.fromCharCode(event.which || event.charCode).match(/[\\dext\\[\\]\\-]/)" required name="phone" id="phonecontactselection" > 

You could use test and a character class and list your characters that you would allow to match.

In this case match one of [ , ] , a character az , dot or a hyphen:

[\][a-z.-]

 <input type="text" maxlength="40" onkeypress="return /[\\][az.-]/.test(String.fromCharCode(event.which || event.keyCode));" required name="phone" id="phonecontactselection" > 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM