gpt4 book ai didi

jquery - 仅验证字段字母 jquery/ajax

转载 作者:行者123 更新时间:2023-11-28 04:07:03 25 4
gpt4 key购买 nike

我正在尝试验证一个只允许输入字母的字段。如果我写一个数字或另一个符号,整个字段将变成红色,我将无法点击“提交”按钮。该按钮将被锁定,直到一切正常。

一个人给了我这个:

$("#form-description").on("keyup", function() {
var text = $(this).val();
var a = 120 - text.length;
var lettersonly = /^[a-zA-Z]+$/;
if (!/^[a-zA-Z\s]*$/.test(text)) {
$(this).parent().css("border", "1px solid red");
}
$("#error-description").text(a), a < 10 && $("#charcount").css({
color: "red"
})
});
$('#herter').on('keydown', function(e) {
if (e.which == 9) { //9 is tab key, 13 is enter key
var text = $(this).val();
if (text.length > 50) {
alert("You have entered too much text. The maximum for this field is 50 characters.")
} else if (text.length < 1) {
alert("Please enter some text.");
}

}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<td><input type='text' class="form-text" id='herter' maxlength="60" name='txtnombre' required /><span class="error-form" id="error-name"></span></td>
<td>
<div>
<input type='text' class="form-text" id="form-description" name="txtdescripcion" />
</div>

<span class="error-form" id="error-description"></span></td>
<div id="charcount">
</div>

如果我写一个数字,该字段会变成红色,但是当我删除该字段上的所有内容时它不会消失。或者例如,如果我写“Hello word4”,如果我删除数字 4,该字段将保持红色:/。

如果您输入数字,它必须显示警报,并且它必须使用 TAB 键或单击该字段来验证每个字段

此外,提交按钮未锁定,如果字段为“红色”,提交按钮仍然有效:/。

不知道该怎么办:S

最佳答案

这应该可以帮助您找到正确的方向。这会将“错误”类添加到具有“验证”类的任何输入。验证字段后,doValidation 将查找任何错误。如果发现错误,按钮将被禁用,如果没有发现错误,它将再次启用按钮。相当直接。

let doValidation = (field) => {
// Check for the amount of none letter chars
if(field.value.replace(/[A-z]/g,"").length)
// If found add error
$(field).addClass('error');
else
// If none found ensure no error
$(field).removeClass('error');

// Check total input errors
if($('.error').length)
// If some are found disable button
$('input[type=button]').attr('disabled','true');
else
// If none are found enable button
$('input[type=button]').removeAttr('disabled');
}

// Runs when field is clicked or focus is lost (Tab)
$('.validate').on('click focusout',function(){
doValidation(this);
});
.error {
border-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="text" class="validate">
<input type="text" class="validate">

<input type="button" value="Submit">

关于jquery - 仅验证字段字母 jquery/ajax,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42908952/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com