简体   繁体   中英

How can I use javascript to index input from a HTML form?

I have a form where you must enter a username, but the username cannot start or end with a period (.). This is what I have so far, I feel like I'm close. I think I am making an error in the.value[0] parts.

    //Checking Username
    if (document.getElementById("uName").value[0] == "." || document.getElementById("uName").value[-1]) {
        document.getElementById("notification4").innterHTML ="Cannot have period at start or end.";
        submitForm = false;
    } else {
        document.getElementById("notification4").innerHTML="";
    }

My second question is how would I be able to stop the same character from repeating twice in a row? For example you can't have (--), (//), (%%), (**) etc. I would prefer a similar method to use like above or with regex.

This is the forms HTML:

        <label for="uName"> Username: </label><br>
        <input type="text" id="uName" name="uName"> <br>
        <div class= "error" id="notification4"></div><br>

You can use regular expression and the RegExp.prototype.test() function:

const regex = /^[.]|[.]$|[^a-zA-Z0-9]{2}/g;
if(regex.test(str)) {
    //code when it matches
} else {
    //code when it doesn't match
}

This checks if the first or last character is a dot (^[.]|[.]$) and if there is any character repeated twice that is not a letter or number ([^a-zA-Z0-9]{2}).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM