简体   繁体   English

如何使用Javascript通过最大值验证texarea

[英]How to validate texarea by max value using Javascript

I need to validate text area as following code,我需要按照以下代码验证文本区域,

my code as follows, here I need set maximum length as 10 and, if user trying to enter more than 10 need to prevent and if it is backspace or delete need to allow for deleting purpose.我的代码如下,这里我需要将最大长度设置为 10,如果用户尝试输入超过 10 需要阻止,如果是退格或删除需要允许删除目的。 and also need to show remaining character count in a paragraph.并且还需要显示段落中的剩余字符数。 But this code not working well.但是这段代码不能很好地工作。 Its not preventing text input after 10.它不会阻止 10 之后的文本输入。

<textarea id="txtxasa" class="message-content" onkeyup="Validate(event,this)"></textarea>
<p id="MsgContentRemainingLimit" class="message-character-limit">10 characters remaining</p>

function Validate(e,vald) {
    var code;
    var txtLength = vald.value.length;
    var remainingContent = 10 - txtLength;
    $('#MsgContentRemainingLimit').text(remainingContent);
    console.log(vald.value.length)

    if (!e) var e = window.event;
    if (e.keyCode) code = e.keyCode;
    else if (e.which) code = e.which; 

    if (txtLength >=10 && (code != 8 || code != 46))
        return false;
}

Have you tried adding maxlength="10" to the textarea .您是否尝试将maxlength="10"添加到textarea I've done it and it works for me.我已经做到了,它对我有用。

In Javascript you can try like this在 Javascript 中,您可以这样尝试

 let element = document.getElementById('input-name'); let countElem = document.getElementById('counter').innerHTML; element.addEventListener('input', function() { let inputvalue = this.value; let maxLength = 10; //disable the input if reached the limit if (inputvalue.length > maxLength) { console.log('maximum character limit reached'); this.disabled = true; } //count the numbers let count = parseInt(countElem, 10); document.getElementById('counter').innerHTML = count - inputvalue.length; if (inputvalue.length > count) { document.getElementById('counter').innerHTML = 0; } });
 <p> <input placeholder="First Name" id="input-name" name="input"> </p> <p>remaining characters:</p><span id="counter" style="font-size:25px; font-weight:600;">10</span><br>

In Html5 you can also use the <input maxlength='10'> to limit characters only as a frontend validation.在 Html5 中,您还可以使用<input maxlength='10'>将字符限制为仅作为前端验证。 onkeyup in your code will not work if the user copy text and right click and paste them.如果用户复制文本并右键单击并粘贴它们,则代码中的onkeyup将不起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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