2017-09-04 45 views

回答

0

雙重驗證HTML中的驗證和表單提交的驗證。

HTML

<input name="numbers" type="text" maxlength="9" size="20" pattern="^\d{9}$" placeholder="9 digits only" /> 

這限制了輸入到9個字符,允許模式匹配9位僅將轉向輸入區域紅色如果不正確,並增加了佔位符文本,以警告用戶。

的JavaScript

有關示例,這裏採用一個簡單的按鈕來輸入驗證表單提交之前:

const button = document.querySelector('button'); 
button.addEventListener('click', formHandler, false); 

function formHandler(e) { 

    // Don't submit the form yet 
    e.preventDefault(); 

    // Grab the form 
    const form = document.forms[0]; 

    // Use the same regex as in the HTML to test the input value 
    if (/^\d{9}$/.test(form.numbers.value)) { 
    console.log('OK') // form.submit() ? 
    } else { 
    console.log('Fail') 
    } 
} 

DEMO

相關問題