js使用正则表达式

参考慕课网示例:

使用js对html输入框内容进行校验:

1. 只能输入5-20个字符,必须以“字母”开头

2. 可以带“数字" “_” “.”的字串

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<style type="text/css">
body, form, input {
    margin: 0;
    padding: 0;
    font-size: 12px
}

body {
    margin-left: 50px
}

form {
    height: 30px;
    line-height: 30px
}

.text {
    height: 20px;
    vertical-align: middle
}

.btn {
    height: 24px;
    width: 50px;
    vertical-align: middle;
    border: 1px solid #333;
    background: #ccc;
}
</style>
</head>
<script type="text/javascript">
window.onload=function(){
    var oBtn=document.getElementById("submitBtn");
    var oInput=document.getElementById('name');
    oBtn.onclick=function(){
        alert(oInput.value);
        var re = /^[a-zA-Z]{1}[w\_.]{4,9}$/g;//5-10个字符,字母开头   
        if(re.test(oInput.value)==false){
            alert("× 格式错误!")
        }
        else{
            alert("√ 格式正确!")
        }
    }
}
</script>
<body>
    <h3>要求:</h3>
    <p>1. 只能输入5-20个字符,必须以“字母”开头</p>
    <p>2. 可以带“数字" “_” “.”的字串</p>
    <br />
    <form>
        <label>用户名:<input id="name" class="text" type="text" /></label> <input
            id="submitBtn" class="btn" type="button" value="验证" />
    </form>
</body>
</html>