JavaScript validation of the form submission

In the daily development we tend to use JavaScript form submission whether legal judgment, so that we can avoid to go to authenticate the server.

First, look at how JavaScript obtain the value of the form element

<form action="#" method="post">
        <span>姓名:</span><input type="text" name="userName" id="name" required/></br>//required表示必须填写该字段 不然提交不了 
        <span>密码:</span><input type="password" name="password" id="password"/></br>
        <span>性别:</span><input type="radio" name="gender" id="boy" value="man"/>男
        <input type="radio" name="gender" id="girl" value="woman"/>女</br>
        <span>科目:</span><input type="checkbox" name="box1" checked/><span>Java</span>
        <input type="checkbox" name="box2" checked/><span>Python</span>
        <input type="checkbox" name="box3"/><span>C++</span>
        <input type="checkbox" name="box4"/><span>PHP</span><br>
        <span>爱好:</span>
        <select name="selector" id="selector">
            <option value="sing">唱</option>
            <option value="dance">跳</option>
            <option value="rap">Rap</option>
            <option value="basketball">篮球</option>
        </select>

    </form>
    <script type="text/javascript">
        let userName = $('#name');
        console.log(userName.val());//获得text/password文本框的值
        let boy_radio = document.getElementById('boy');
        let girl_radio = document.getElementById('girl');
        //我们查看选择框(单选框、复选框) 不能直接得到选择元素的值
        //需要遍历它的所有选择节点 查看是否checked = true 如果是 则被选中。
        console.log(boy_radio.checked);//查看boy_radio这个元素是否被选中
        console.log(girl_radio.checked);//查看girl_radio这个元素是否被选中
        girl_radio.checked = true;//还可以人为的控制他们是否被选中
    </script>

Onsubmit has a property that it can be set to a function to control whether the form is submitted by returning true or false in the form tag

<form action="#" method="post" onsubmit="return fun1()">
        .....
</form>

<script type="text/javascript">
        function fun1(){
           .....
            //如果校验通过 返回true允许通过
            //否则返回false 不允许通过
            return true;
	}
</script>

For the user password privacy this one if we do not deal with any form submitted by crawling (Ethereal) we can see the values of all elements of the form we submitted this of course is not possible so we need this password Reception value box processing

Use md5 password encryption algorithm

	<script src="https://cdn.bootcss.com/blueimp-md5/2.10.0/js/md5.min.js"></script> //引入文件
	
	<script type="text/javascript">
        function fun1(){
            let userName = $('#name');
            let password = $('#password');
            password.val(md5(password.val()));//将密码框中的值使用md5算法加密
		}
Published 53 original articles · won praise 0 · Views 1953

Guess you like

Origin blog.csdn.net/XXuan_/article/details/104174352