簡體   English   中英

有沒有辦法使Regex函數檢查名字和姓氏?

[英]Is there a way to make a Regex function to check a first and last name?

我目前正在為我的編碼課做作業(我是初學者)。 任務是創建一個具有2個輸入的HTML頁面,一個用於名字,一個用於姓氏,並創建一個提交按鈕,單擊該按鈕可檢查名字和姓氏是否都以大寫字母開頭且至少包含1個字符。 當它們都與正則表達式匹配時,將使用警報,並且控制台將記錄日志。 如果不這樣做,則會使用其他警報,並且控制台不會記錄日志。 當我完成html和腳本的編寫后,我在兩個輸入中都鍵入了一個名稱,該名稱應與正則表達式匹配,但是它只會針對不正確的輸入發出警報。 有問題,但我找不到。


function regexChecker(firstName, lastName) {
    firstName = document.getElementById("firstName").innerHTML;
    lastName = document.getElementById("lastName").innerHTML;
    let firstNameRegex = /^[A-Z][a-z]*$/;
    let lastNameRegex = /^[A-Z][a-z]*$/;
    if (firstName.match(firstNameRegex) && lastName.match(lastNameRegex)) {
        alert('Yay! Your inputs were all correct!' );
        console.log(true);
    }
    else {
        alert('Oh no! Thats an invalid format!' );
        console.log(false);
    }
}

在我未提供的鏈接html中,每個名稱都有兩個輸入以及一個按鈕。 我在第一個輸入了以撒的名字,在第二個輸入了丹尼爾斯的名字。 我希望警報為“是!您的輸入都正確!”,但我卻收到了“哦,不!那是無效的格式!”

您犯了兩個錯誤:

  • 使用value代替innerHTML <input>沒有innerHTML
  • match返回一個始終為真的數組。 甚至Boolean([]) => true 您應該使用test()而不是match
  • 您的RegExp不會傳遞包含大寫字母的字符串。 您應該使用/^[AZ][a-zA-Z]*$/

這是代碼。

function regexChecker(firstName, lastName) {
    firstName = document.getElementById("firstName").value;
    lastName = document.getElementById("lastName").value;
    let firstNameRegex = /^[A-Z][a-zA-Z]*$/;
    let lastNameRegex = /^[A-Z][a-zA-Z]*$/;
    if (firstNameRegex.test(firstName) && lastNameRegex.test(lastName)) {
        alert('Yay! Your inputs were all correct!' );
        console.log(true);
    }
    else {
        alert('Oh no! Thats an invalid format!' );
        console.log(false);
    }
}

注意 :兩個字符串都具有相同的正則表達式/^[AZ][az]*$/因此您可以使用every()來檢查兩者。

function regexChecker(firstName, lastName) {
    firstName = document.getElementById("firstName").value;
    lastName = document.getElementById("lastName").value;
    let regex = /^[A-Z][a-zA-Z]*$/;
    if ([firstName,lastName].every(x => regex.test(x))) {
        alert('Yay! Your inputs were all correct!' );
        console.log(true);
    }
    else {
        alert('Oh no! Thats an invalid format!' );
        console.log(false);
    }
}

您可以使用此正則表達式:

/^([A-Z][a-z]*)+$/

它將測試它以大寫字母開頭,然后是小寫字母,並且至少一個字母長。

您可以將regexp與.test()以獲取true / false值。

 let regexp = /^([AZ][az]*)+$/ document.names.addEventListener('submit', e => { e.preventDefault() let firstValid = regexp.test(document.names.first.value) let lastValid = regexp.test(document.names.last.value) // Sanity check console.log(firstValid, lastValid) if (!firstValid) alert('First name is invalid!') else if (!lastValid) alert('Last name is invalid!') else alert('Both are valid!') }) 
 <form name="names"> <input type="text" name="first" placeholder="First Name"> <input type="text" name="last" placeholder="Last Name"> <p> <input type="submit" value="Check Names"> </p> </form> 

暫無
暫無

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

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