preface
This is the 5th day of my participation in the August More Text Challenge. It coincides with the challenge of Digging Gold in August. Today, I would like to share with you some information about using Vue to realize user registration, verify data format and display password strength in real time. I hope this small demo can give a little inspiration to beginners of Vue and help you better understand and learn. Come on, mutual encouragement!
Page style presentation
Demand analysis
Except the default gender is male, other fields are mandatory, otherwise click the registration button will not be submitted, at the same time remind the user to fill in, and focus the mouse on the corresponding unfilled input box, fill in the wrong format is the same.
Such as:
The age field is automatically calculated after the date of birth is entered. You do not need to enter this field and can set it to Disabled.
Effect:
When the user presses the key to enter the password, the real-time monitoring judgment will be started. The password length must be at least 6 and not more than 16 digits. The password strength display effect will be displayed if the conditions are met.
Example:
Code implementation
HTML structure + simple inline CSS style
<div id="register"> <table> <tr> <th> </th> <td><input type="text" ID ="username" placeholder=" autocomplete="off" V-model ="user.username" <tr> <th> name: </th> <td><input type="text" id="name" placeholder=" autocomplete="off" V-model ="user.name"/></td> </tr> <tr> <th> Gender: </th> < TD > <label> <input type="radio" name="sex" value="1" checked V-model ="user.gender"/> Male </label> <label> <input type="radio" name="sex" value="0" V-model ="user.gender"/> Female </label> </ TD > </tr> <tr> <th> date of birth: </th> < TD > <label> <input type="date" id="birthday" placeholder=" v-model="user.birthday"/> </label> </ TD > </tr> < tr > < th > age: < / th > < td > < input type = "number" id = "age" disabled v - model = "user. Age" / > < / td > < / tr > < tr > < th > phone number: </th> < TD > <input type="tel" ID ="mobile" placeholder=" autocomplete="off" V-model ="user.mobile" <tr> <th> </th> < TD ><input type="password" id="password" placeholder=" autocomplete="off" V-model ="user.password" v-on:keyup="strengthShow"/></td> </tr> <tr> <th style="width: max-content;" > < / th > < td > < span id = "weak" > weak < / span > < span id = "medium" >, < / span > < span id = "strong" > strong < / span > < / td > < / tr > < tr > < th style="width: max-content;" ></th> <td><span style="color: red; font-size: smaller;" >{{msg}}</span></td> </tr> <tr> <th style="width: max-content;" ></th> <td> < button@click ="checkForm"> </ buttononclick ="history.back()" style="display: inline-block; Margin - left: 70 px "> return < / button > < / td > < / tr > < / table > < / div >Copy the code
Here do not do too much explanation, the code is not complex, mainly password strength display bar style:
#weak,
#medium,
#strong {
display: inline-block;
height: 15px;
width: 48px;
border-top: 4px solid gainsboro;
margin-left: 3px;
font-size: 12px;
text-align: center;
}
Copy the code
Vue part
var vm = new Vue({ el: '#register', data: { user: { username: null, name: null, gender: 1, birthday: null, age: 0, mobile: null, password: null }, msg: null }, methods: { checkForm: function () { const emptyKey = isEmptyInput(); Switch (emptyKey) {case 'username': msgForUser(' username cannot be empty! ', emptyKey); break; Case 'name': msgForUser(' name cannot be empty! ', emptyKey); break; Case 'birthday': msgForUser(' birthday cannot be empty! ', emptyKey); break; Case 'mobile': msgForUser(' mobile phone cannot be empty! ', emptyKey); break; Case 'password': msgForUser(' password cannot be empty! ', emptyKey); break; Default: // If (! (/ ^ (1) [345789] \ d {9} $/. The test (this) user) mobile))) {this. MSG = 'phone number format is wrong! '; } else if (this. User. The password. Length < 6 | | this. User. The password. The length > 16) {this. MSG = 'password length must be between 6 and 16! Const user = this.user; const user = this.user; const user = this.user; $.ajax({ type: 'POST', url: './registerUser', data: user, success: function (data) { handleRegister(data); }, error: function (error) { alert(error); }}); } } }, strengthShow: The function () {/ / password strength weak real-time display / / password: are all Numbers or all letters, 6-16 characters const weakReg = / ^ [0-9] {June 16th} $| ^ [a zA - Z] 6 16th} {$/; Const mediumReg = /^[a-za-z0-9]{6,16}$/; // Const mediumReg = /^[a-za-z0-9]{6,16}$/; Const strongReg = /^\w{6,16}$/; // Strong password: a string of 6 to 16 characters consisting of digits, 26 letters, or underscores var password = this.user.password; if(null ! == password) { if(password.length >= 6 && password.length <= 16) { if(password.match(weakReg)) { $('#weak').css('borderTopColor', 'yellow'); }else if(password.match(mediumReg)) { $('#weak').css('borderTopColor', 'yellow'); $('#medium').css('borderTopColor', 'blue'); }else if(password.match(strongReg)) { $('#weak').css('borderTopColor', 'yellow'); $('#medium').css('borderTopColor', 'blue'); $('#strong').css('borderTopColor', 'green'); } }else { $('#weak').css('borderTopColor', 'gainsboro'); $('#medium').css('borderTopColor', 'gainsboro'); $('#strong').css('borderTopColor', 'gainsboro'); }}}}, watch: {user: {handler: function () {var birthday = this.user.birthday; if(birthday ! == null) { var gap = getGrowAge(birthday); Var index = gap. IndexOf (' age '); this.user.age = parseInt(gap.substring(0,index)); } this.msg = null; }, deep: true } } });Copy the code
The Vue code defines a user object and a reminder for the user, defines two methods, one for form validation, and binds the registration button to a click event via @click=”checkForm”, which is v-on:click=”checkForm”. Click the button and verify from top to bottom.
The above code contains three wrapped functions, which loop through the registered user object to determine whether the property value is null or a space string. In either case, the loop ends and returns the property name, and the msgForUser() function sends a reminder to the user. And find the input form by attribute name to achieve focus, waiting for the user to enter again. The third function displays a successful registration message and implements a page waiting jump.
The three functions are implemented as follows:
Function msgForUser(text, id) {vm. MSG = text; const obj = $(`#${id}`); obj.focus(); } key function isEmptyInput() {const entries = object.entries (vm.user); var key = null; for(const [k, v] of entries) { if(v === null || (v.toString()).match(/^[ ]*$/)) { key = k; break; } } return key; } function handleRegister(data) {alert(data.msg); SetTimeout (function () {window.location.href = '.. /index.html'; }, 750); }Copy the code
V-model =”user.password” V-ON :keyup=”strengthShow” Password With bidirectional binding, you can add keypress events to dynamically monitor password status and display password strength in real time.
So how do you dynamically calculate the age based on the date of birth entered?
Write a handy utility function that converts the current time to seconds minus the number of seconds after the birthday conversion, and then converts the resulting difference to the number of years, months, hours, and even minutes. Pay attention to leap years and get the number of days in different months in different years.
Function getGrowAge(birthday){var now = new Date(); var year = now.getFullYear(); var month = now.getMonth() + 1; var day = now.getDate(); var hour = now.getHours(); var minute = now.getMinutes(); var second = now.getSeconds(); var myDate = new Date(birthday); var myYear = myDate.getFullYear(); var myMonth = myDate.getMonth() + 1; var myDay = myDate.getDate(); var myHour = myDate.getHours(); var myMinute = myDate.getMinutes(); var mySecond = myDate.getSeconds(); var gapSecond = second - mySecond; if(gapSecond < 0){ minute -= 1; gapSecond = 60 - mySecond + second; } //gapSecond = gapSecond<10? ("0"+gapSecond): gapSecond; var gapMinute = minute - myMinute; if(gapMinute < 0){ hour -= 1; gapMinute = 60 - myMinute + minute; } //gapMinute = gapMinute<10? ("0"+gapMinute): gapMinute; var gapHour = hour - myHour; if(gapHour < 0){ day -= 1; gapHour = 24 - myHour + hour; } //gapHour = gapHour<10? ("0"+gapHour): gapHour; var gapDay = day - myDay; if(gapDay < 0){ month -= 1; gapDay = getDaysOfMonth(birthday) - myDay + day; } //gapDay = gapDay<10? ("0"+gapDay): gapDay; var gapMonth = month - myMonth; if(gapMonth < 0){ year -= 1; gapMonth = 12 - myMonth + month; } //gapMonth = gapMonth<10? ("0"+gapMonth): gapMonth; var gapYear = year - myYear; if(gapYear < 0){ gapYear = 0; } var dateStr = (gapYear>0? GapYear :'0') + '0' + (gapMonth>0? GapMonth :'0') + 'month' + (gapDay>0? GapDay :'0') + 'day' + (gapHour>0? GapHour :'0') + 'hour' + (gapMinute>0? GapMinute :'0') + 'minute' + (gapSecond>0? GapSecond :'0') + 'second '; return dateStr; Function getDaysOfMonth(dateStr){var date = new date (dateStr); var year = date.getFullYear(); var mouth = date.getMonth() + 1; var day = 0; if(mouth == 2) { day= isLeapYear(year) ? 29:28; } else if(mouth == 1 || mouth == 3 || mouth == 5 || mouth == 7 || mouth == 8 || mouth == 10 || mouth == 12) { day= 31; } else { day= 30; } return day; } function isLeapYear(year){return (year%4==0 && year%100! =0)||(year%400==0); }Copy the code
How easy is it to put the written function into a JS file, import it in the page, and combine it with Vue’s data binding to achieve the desired effect? !
At the end
Writing is not easy, welcome everyone to like, comment, your attention, like is my unremitting power, thank you to see here! Peace and Love.