简体   繁体   中英

HTML input accept only numbers and email

如何设置html输入以仅接受数字和电子邮件ID?

<input id="input" type="text" />
<input id="input" type="number" />
<input id="input" type="email" />

Check this info out on w3schools

... I see you want the same input, so you would stick with text then check the input using regex

\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b.

then whatever regex you need to validate your number

您可以将输入设置为type="email"type="tel"

You can run a simple regex against the phone number and the email. That will most likely not catch all issues but it will give you a starting point.

Pseudo code:

//if input is phone
  // do something
// else if input is email
  // do something else
// else (when it is neither)
  // throw an error

or you can even shorten this

// if input is phone or input is email 
  // do something
//else
  //trow error

You can find a ton of regex solutions in the library at regex101.com. There is a whole bunch of email and phone number validators.

One that is supposed to check both (and I didn't look to deeply into the regex) is: \\(^\\+[0-9]{9,15}$)|(^.+@.+\\..+$)\\i

This should be true if the input string is a phone or email. However, like I said above, it most likely needs refinement.

As mentioned above in the comments, this should work if you want to accept both 8-digit phone numbers and email addresses:

HTML form code:

<form onsubmit="return validateInput()">
  <input type="text" name"mail_or_phone"/>
</form>

JS validation:

function validateInput()
{
  var fieldValue= document.getElementById("mail_or_phone").value;

  // taken from this SO post: http://stackoverflow.com/questions/7126345/regular-expression-to-require-10-digits-without-considering-spaces      
  var phoneValidation= /^([\s\(\)\-]*\d[\s\(\)\-]*){8}$/; 
  var mailValidation= /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

  if (fieldValue.match(phoneValidation)) {
    // correct phone structure
    return true;
  } else if (fieldValue.match(mailValidation)) {
    // correct mail format
    return true;
  } else {
    // incorrect structure
    return false;
  }
}

Here's a fiddle showing an example of the above code. In case of an incorrect answer you should show some kind of warning (not included in the code).

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