Improvement of native custom validation of html5 form

In my last blog https://my.oschina.net/u/3470006/blog/1505758 html5 form native custom validation, there is actually a problem with the username. When the username is entered in pinyin, it will force the input of letters and break the word limit , although the background revalidation can intercept illegal input, but this experience is still not good, I decided to improve

First, change the html to the following

            <form method="post" action="Login/Register" onsubmit="CheckUserName()">
                <input type="text" id="username" placeholder="用户名(只能是数字或字母)" maxlength="25" required autofocus
                       name="UserName" onblur="if(value!='')CheckUserName()">
                <input type="password" id="password" placeholder="密码" maxlength="25" required minlength="6"
                       name="Password" oninput="if(value.length>5)CheckPassword()"><span style="color:#23de17;"
                                                                                         id="ViewPasswordRule"
                                                                                         onclick="ShowPasswordRule()">查看密码规则</span><br>
                <button type="submit" id="Register">确认注册</button>
            </form>

Username standard: default prompt, maximum 25, required, auto focus

I changed the function that detects the username to the following two

function CheckUserName() {
    var UserNameBox=document.getElementById("username")
    var reg=new RegExp("^[A-Za-z0-9]+$")
    if(reg.test(UserNameBox.value)){
        UserNameBox.setCustomValidity("")
        CheckUserNameIsExits()
    }
    else{
        UserNameBox.setCustomValidity("用户名只能为字母或数字")
    }
}
function CheckUserNameIsExits() {
    $.get("Index/Index/CheckUserIsExitsByUserName", {UserName: document.getElementById("username").value}, function (a) {
        var UserNameBox = document.getElementById("username")
        if (a === true) {
            UserNameBox.setCustomValidity("该用户已存在")
        } else {
            UserNameBox.setCustomValidity("")
        }
    })
}

In CheckUserName, a regular expression to detect whether it is a number or a letter is added, and a prompt that "username can only be a letter or a number" is given. After this test is passed, the detection of the existence of the user is given. I have not encapsulated this interface yet.

Detecting the username I have detected when the focus is lost and the form is submitted, if(value!="") is to not override the native required prompt

In this way, the front-end detection of the user name has been perfected. If the user wants to kill or the villain wants to destroy, it still needs to be re-verified on the server side.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325431280&siteId=291194637