我有一个文本框,应该只接受文本而不是数值,还有一些其他要求。
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>');
}
}
答案 0 :(得分: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 :(得分:-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>