簡體   English   中英

正則表達式只允許正整數並在 jQuery 中檢查有效性

[英]Regex to allow only positive whole numbers and checking validity in jQuery

我的 HTML 中有兩個這樣的輸入字段:

<input type="text" class="txtminFeedback" pattern="^\d+([\.\,][0]{2})?$" placeholder="Minimum Feedback">

<input type="text" class="txtmaxFeedback" pattern="^\d+([\.\,][0]{2})?$" placeholder="Maximum Feedback">

我已經嘗試了幾種正則表達式模式,如下所示:

^\d+([\.\,][0]{2})?$

or

(^[0-9]+$|^$)

or

/^\d*$/

這些都不適用於 jQuery 中的以下代碼:

if ($('.txtminFeedback').val() == "" && $('.txtmaxFeedback').val() == "") {
    if ($('.txtmin')[0].checkValidity() && $('.txtmax')[0].checkValidity()) {
        if ($('.txtSearch').val() == "") {
            ShowMessage("Please enter the search term!");
            return;
        }
        else {
            PostAndUpdate($('.txtSearch').val(), $('input[name=type]:checked').val(), $('input[name=shipping]:checked').val(), $('input[name=condition]:checked').val(), $('.txtmin').val(), $('.txtmax').val(), $('.txtNegativeKeywords').val(), $('.txtminFeedback').val(), $('.txtmaxFeedback').val());
        }
    } else {
        ShowMessage("You have entered incorrect value for minimum or maximum price!");
        return;
    }
} else if (!$('.txtminFeedback')[0].checkValidity() || !$('.txtmaxFeedback')[0].checkValidity())
{
    ShowMessage("Please enter only positive value for minimum and maximum feedback.");
    return;
}

如果需要,用戶可以將 txtminfeedback 和 txtmaxfeedback 留空。 但是,如果他決定輸入一些值,則必須輸入兩個字段,並且只需要輸入整數正數(從 0 到 400 萬)。

我在這里做錯了什么?

最后這樣做了:

 pattern="^(\s*|\d+)$"


 if ($('.txtminFeedback')[0].checkValidity()==false || $('.txtmaxFeedback')[0].checkValidity()==false) {
                ShowMessage("Please enter only positive value for minimum and maximum feedback.");
                return;
            }
            if ($('.txtmin')[0].checkValidity() && $('.txtmax')[0].checkValidity()) {
                if ($('.txtSearch').val() == "") {
                    ShowMessage("Please enter the search term!");
                    return;
                }
                else {
                    PostAndUpdate($('.txtSearch').val(), $('input[name=type]:checked').val(), $('input[name=shipping]:checked').val(), $('input[name=condition]:checked').val(), $('.txtmin').val(), $('.txtmax').val(), $('.txtNegativeKeywords').val(), $('.txtminFeedback').val(), $('.txtmaxFeedback').val());
                }
            } else {
                ShowMessage("You have entered incorrect value for minimum or maximum price!");
                return;
            }

以防萬一將來有人可能需要它。

干杯 =)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM