开发者

How to restrict paste values in form?

开发者 https://www.devze.com 2023-03-03 05:28 出处:网络
I have a form that contains a phone number field <input name=\"phNumber\" type=\"text\" class=\"number开发者_JAVA技巧sonly\"/>

I have a form that contains a phone number field

<input name="phNumber" type="text" class="number开发者_JAVA技巧sonly"/>

using js i can allow only number but,i wanna to restrick paste value from mouse...

{NOTE: No Validation is required in this field}


You can bind an event to your input component:

$('selector').bind('paste', function() {
  return false;
});

See for reference: jQuery API - bind


You can respond to the change event, removing any non-digits.

$("input.numbersonly").change(function() {
    this.value = this.value.replace(/\D/g, "");
});

That uses a regular expression (/\D/g) to match all non-digits and replace them with the replacement string (in this case, nothing — ""). The \D part is the "non-digit" part, and the g is the flag meaning "global" (throughout the string).


Off-topic: I really, really wouldn't disallow all non-digits in a phone number field. People are used to writing phone numbers with spaces, hyphens, perhaps parentheses, maybe even the plus sign (e.g., +1 (408) 123-4567). Phone numbers can be very difficult to read (and therefore to type correctly) if you remove these cues. You do want your users to type the number correctly, right? In which case, I would keep the validation pretty open.

0

精彩评论

暂无评论...
验证码 换一张
取 消