gpt4 book ai didi

javascript - 在输入字段上使用 RegEx 添加和删除验证

转载 作者:行者123 更新时间:2023-12-03 05:26:51 26 4
gpt4 key购买 nike

点击“添加”按钮后会弹出一个对话框。有 2 个字段,MR ID 和 vendor ID。 MR ID 是一个下拉菜单,不需要任何形式的验证。 vendor ID 是文本输入,需要验证。它只能是数字,并且不能有 2 个相同的 vendor ID。它们必须都是独一无二的。到目前为止,我的代码无法验证 vendor ID。

对话框的 HTML/PHP:

<div id="dialog-form" title="Add Supplier ID">
<p class="validateTips">All form fields are required.</p>

<!-- Dialog box displayed after add row button is clicked -->
<form>
<fieldset>
<label for="mr_name">MR_ID</label>
<select name="mr_id" id="mr_id_dialog" class="text ui-widget-content ui-corner-all" value="300">
<?php foreach($user->fetchAll() as $user1) { ?>
<option selectedvalue="1">
<?php echo $user1['MR_ID'];?>
</option>
<?php } ?>
</select><br><br>
<label for="buyer_id">Supplier ID</label>
<input type="text" name="supp_id" id="supplier_id" class="text ui-widget-content ui-corner-all" value="99">

<!-- Allow form submission with keyboard without duplicating the dialog button -->
<input type="submit" id="submit" tabindex="-1" style="position:absolute; top:-1000px">
</fieldset>
</form>
</div>

JavaScript:

// ----- Dialog Box for adding supplier id -----

$( function() {


$("#insertButton").on('click', function(e){
e.preventDefault();
});

var dialog, form,

mr_id_dialog = $( "#mr_id_dialog" ),
supplier_id = $( "#supplier_id" ),
allFields = $( [] ).add( mr_id_dialog ).add( supplier_id ),
tips = $( ".validateTips" );
console.log(allFields);

function updateTips( t ) {
tips
.text( t )
.addClass( "ui-state-highlight" );
setTimeout(function() {
tips.removeClass( "ui-state-highlight", 1500 );
}, 500 );
}

function checkRegexp( o, regexp, n ) {
if ( !( regexp.test( o.value ) ) ) {
o.addClass( "ui-state-error" );
updateTips( n );
return false;
} else {
return true;
}
}

function addVendor() {
var valid = true;
allFields.removeClass( "ui-state-error" );
// ----- Validation for each input in add row dialog box -----
//valid = valid && checkRegexp( mr_id_dialog, /^(0|[1-9][0-9]*)$/, "Please enter a valid MR ID" );
valid = valid && checkRegexp( supplier_id, /^(0|[1-9][0-9]*)$/, "Please enter a valid Supplier ID" );
console.log(allFields);
if ( valid ) {
var $tr = $( "#index_table tbody tr" ).eq(0).clone();
var dict = {};
var errors = "";
$.each(allFields, function(){
$tr.find('.' + $(this).attr('id')).html( $(this).val()+"-"+supplier_id );
var type = $(this).attr('id');
var value = $(this).val();
console.log(type + " : " + value);
// ----- Switch statement that provides validation for each table cell -----
switch (type) {
case "mr_id_dialog":
dict["MR_ID"] = value;
break;
case "supplier_id":
dict["Supp_ID"] = value;
break;
}
});
$( "#index_table tbody" ).append($tr);
dialog.dialog( "close" );
console.log(dict);

var request = $.ajax({
type: "POST",
url: "insert.php",
data: dict
});

request.done(function (response, textStatus, jqXHR){
if(JSON.parse(response) == true){
console.log("row inserted");
} else {
console.log("row failed to insert");
console.log(response);
}
});

// Callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
console.error(
"The following error occurred: "+
textStatus, errorThrown
);
});

// Callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {

});


}
return valid;
}

var dialog = $( "#dialog-form" ).dialog({
autoOpen: false,
height: 400,
width: 350,
modal: true,
buttons: {
"Add Supplier ID": addVendor,
Cancel: function() {
dialog.dialog( "close" );
}
},
close: function() {
form[ 0 ].reset();
allFields.removeClass( "ui-state-error" );
}
});

form = dialog.find( "form" ).on( "submit", function( event ) {
event.preventDefault();
addVendor();
});

$( "#insertButton" ).button().on( "click", function() {
dialog.dialog({
position: ['center', 'top'],
show: 'blind',
hide: 'blind'
});
dialog.dialog("open");
});
});

应通过的示例:

349348
2
1234

不应通过的示例:

01234
123 45 67
No hyphens, dashes, etc. Numbers only.

最佳答案

the jQuery documentation for the id-selector :

Calling jQuery() (or $()) with an id selector as its argument will return a jQuery object containing a collection of either zero or one DOM element.

不要使用 supplier_idvalue 属性,而是使用 .val()函数 - 因为 .val() 将:

Get the current value of the first element in the set of matched elements

所以更新你的函数 checkRegexp() 像这样:

function checkRegexp( o, regexp, n ) {
if ( !( regexp.test( o.val() ) ) ) {
...

此外,在生成 option 时对于选择列表的元素,selectedvalue 不是有效属性。有 4 个特定于 option 元素的属性(除了 global attributes ):disabledlabelselected

$(function() {
$("#insertButton").on('click', function(e){
e.preventDefault();
});
var dialog, form,
mr_id_dialog = $( "#mr_id_dialog" ),
supplier_id = $( "#supplier_id" ),
allFields = $( [] ).add( mr_id_dialog ).add( supplier_id ),
tips = $( ".validateTips" );

function updateTips( t ) {
tips
.text( t )
.addClass( "ui-state-highlight" );
setTimeout(function() {
tips.removeClass( "ui-state-highlight", 1500 );
}, 500 );
}

function checkRegexp( o, regexp, n ) {
if ( !( regexp.test( o.val() ) ) ) {
o.addClass( "ui-state-error" );
updateTips( n );
return false;
} else {
return true;
}
}

function addVendor() {
var valid = true;
allFields.removeClass( "ui-state-error" );
// ----- Validation for each input in add row dialog box -----
valid = valid && checkRegexp( supplier_id, /^([1-9][0-9]*)$/g, "Please enter a valid Supplier ID" );
if ( valid ) {
var $tr = $( "#index_table tbody tr" ).eq(0).clone();
var dict = {};
var errors = "";
$.each(allFields, function(){
$tr.find('.' + $(this).attr('id')).html( $(this).val()+"-"+supplier_id );
var type = $(this).attr('id');
var value = $(this).val();
// ----- Switch statement that provides validation for each table cell -----
switch (type) {
case "mr_id_dialog":
dict["MR_ID"] = value;
break;
case "supplier_id":
dict["Supp_ID"] = value;
break;
}
});
$( "#index_table tbody" ).append($tr);
dialog.dialog( "close" );
}
$('#console').append('valid: '+valid+'<br />');
}

var dialog = $( "#dialog-form" ).dialog({
autoOpen: false,
height: 400,
width: 350,
modal: true,
buttons: {
"Add Supplier ID": addVendor,
Cancel: function() {
dialog.dialog( "close" );
}
},
close: function() {
form[ 0 ].reset();
allFields.removeClass( "ui-state-error" );
}
});

form = dialog.find( "form" ).on( "submit", function( event ) {
event.preventDefault();
addVendor();
});

$( "#insertButton" ).button().on( "click", function() {
dialog.dialog({
position: ['center', 'top'],
show: 'blind',
hide: 'blind'
});
dialog.dialog("open");
});
});
#console {
float: right;
}
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/flick/jquery-ui.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<button id="insertButton">Insert</button>
<div id="dialog-form" title="Add Supplier ID">
<p class="validateTips">All form fields are required.</p>
<!-- Dialog box displayed after add row button is clicked -->
<form>
<fieldset>
<label for="mr_name">MR_ID</label>
<select name="mr_id" id="mr_id_dialog" class="text ui-widget-content ui-corner-all" value="300">
<option value="1">1</option>
<option value="2">2</option>
</select>
<br />
<br />
<label for="buyer_id">Supplier ID</label>
<input type="text" name="supp_id" id="supplier_id" class="text ui-widget-content ui-corner-all" value="99" />
<!-- Allow form submission with keyboard without duplicating the dialog button -->
<input type="submit" id="submit" tabindex="-1" style="position:absolute; top:-1000px" />
</fieldset>
</form>
</div>
<div id="console"></div>

编辑:在您的评论中,您提到它大部分工作正常,尽管它不接受零后跟其他数字,但它确实接受单个 0 (即 0)。如果您从正则表达式中删除零和管道,那就足够了。所以正则表达式来自:

/^(0|[1-9][0-9]*)$/

/^([1-9][0-9]*)$/

var nums = ['123', '99', '01234', '0', '00', '993 2'];
var pattern = /^([1-9][0-9]*)$/;
nums.forEach(function(numberString) {
console.log('num: ',numberString,' pattern match: ',pattern.test(numberString));
});

关于javascript - 在输入字段上使用 RegEx 添加和删除验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41109343/

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