簡體   English   中英

不要處理 <form> 如果 <input> 不包含下划線

[英]Don't process the <form> if the <input> DOESN'T contain an underscore

形成:

<form action="goto.php" method="post" name="myform" id="myform" onsubmit="return formSubmit(this);" class="form-wrapper cf">
  <input name="statusid" autocomplete="off" id="statusid" placeholder="Enter ID Here" type="text">
  <input name="submit_btn" class="submit" id="submit_btn" value="" placeholder="submit" >
</form>

演示-http://jsfiddle.net/FEF7D/4/

一些用戶提交的ID中僅包含數字(例如981734844)。 並且某些用戶提交的ID帶有下划線“ _”(不帶引號)(例如28371366_243322)。

我想做的是不允許提交ID僅包含數字的用戶(例如89172318)來處理表單操作。

換一種說法:

82174363278423:不允許處理表單操作

21489724893249_2918423:允許處理表單操作

有可能這樣做嗎?

提前致謝。

嘗試這個...

function formSubmit(form) {
    // create a regex to test for the numbers + underscore + numbers pattern
    var rx = /^\d+_\d+$/,
        test = rx.test(form.statusid.value);

    test || alert('You need to enter an ID with underscore in it.');
    return test;
}

演示-http://jsfiddle.net/FEF7D/7/

您需要使用Java腳本驗證,並且可以使用以下代碼:

  if ( String.indexOf('_') != -1 ) {
        // your form processing code..
  }

是的,你可以這么做。 有許多解決方案。 例如,您可以使用下划線作為拆分分隔符將輸入字符串拆分為一個數組,如果您的數組有兩個條目,則說明您只有一個下划線。 例如這樣的事情(未經演示的片段進行說明-您還需要為數組的每個部分添加數字檢查,因此如果采用這種方法,您可能希望將拆分分配給變量):

$('form').submit(function(event)
{
    if (myinputvar.split('_').length ! = 2)
    {
        event.preventDefault();
        return false;
    }
    // do the rest of your submission here
});

您可以在表單的onsubmit中進行任何表單驗證。

的HTML

<form name="myform" id="myform" onsubmit="return formSubmit(this);" class="form-wrapper cf" action="goto.php" method="post">
  <input name="statusid" autocomplete="off" id="statusid" placeholder="Enter ID Here" type="text">
  <input type="submit" name="submit_btn" class="submit" id="submit_btn" value="" placeholder="submit" >
</form>

的JavaScript

// Do validation of form
function formSubmit(formObj) {
    // Only allowable character is numeric or underscore 
    if (!/^[_0-9]*$/.test(formObj.statusid.value)) {
        return false;
    }
    return true;
}

上面的兩個答案將起作用(僅去除Neil的jquery)。 另一種選擇是

 function formSubmit(form){ var statusid=document.getElementById("statusid"); if(statusid.value.search("_")===-1){ alert('ID must have an underscore "_".'); } }; 

不幸的是,由於某種原因,我無法使它與jsfiddle一起使用,它告訴我formSubmit is not a function ,但顯然是。 無論哪種方式,javascript都可以對字符串使用“搜索”方法。

暫無
暫無

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

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