阻止文本框输入数值,使用jquery仅接受最少50个字符的文本

问题描述 投票:0回答:2

我有一个文本框应该只接受文本而不是数字值,还有一些额外的要求。

1) I need minimum 50 characters.
2) Extra space replace with single space
3) Only take text and remove only numbers if type

下面的代码不适用于“不接受数字”的要求,但对于其他要求它工作正常。

<textarea  
        id="chq_not_submit_reason" 
        class="textarea_rec"
        onblur="validate($(this).val())"
        placeholder="Please Enter your comments here"
></textarea>

JS

function validate(val) {
    if (val.match(/[^A-Za-z'. .]/g)) {
        val = val.replace(/[^A-Za-z'. .]/g, '');    // not allow numbers if enter numeric value erase only numbers not text
    }

    if (val === '') {
        $(".show_err").html('<p style="color:red;">Don\'t leave this field blank</p>');
    } else if (val.replace(/\s/g, "").length < 50) { // allow single space  with minimum 50 characters
        $(".show_err").html('<p style="color:red;">Minimum 50 characters required</p>');
    }   
 }
javascript jquery
2个回答
0
投票

$('#chq_not_submit_reason').on('keyup', handleOnKeyup);

function handleOnKeyup() {
  $(this).val(
    $(this).val()
      .replace(/\d/g, '') // Removes numeric characters
      .replace(/ +/g, ' ') // Replaces multispaces by single space
  );
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea  id="chq_not_submit_reason" class="textarea_rec" placeholder="Please Enter your comments here" maxlength="50" ></textarea>
<div class="show_err"></div>

-1
投票

$('#chq_not_submit_reason').on('keyup', handleOnKeyup);
$('#chq_not_submit_reason').on('blur', handleOnBlur);

function handleOnKeyup() {
  $(this).val(
    $(this).val()
      .replace(/\d/g, '') // Removes numeric characters
      .replace(/ +/g, ' ') // Replaces multispaces by single space
  );
}

function handleOnBlur() {
  if ($(this).val().length < 50) {
    $('.show_err').html(`<p style="color:red;">Minimum 50 characters required.</p>`);
  } else {
    $('.show_err').html('');
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea  id="chq_not_submit_reason" class="textarea_rec" placeholder="Please Enter your comments here" minlength="50" ></textarea>
<div class="show_err"></div>
© www.soinside.com 2019 - 2024. All rights reserved.