Home > Web Front-end > JS Tutorial > js form validation function currently popular error message_javascript skills

js form validation function currently popular error message_javascript skills

WBOY
Release: 2016-05-16 18:51:11
Original
923 people have browsed it

Some time ago, I wrote a js data verification, js email verification, js url verification, js length verification, js digital verification and other pop-up dialog boxes. However, that kind of unfriendly method is not very popular now, so I rewrote one, A better encapsulated and more friendly layer form
is shared with everyone. If you have any bugs in using it, please leave me a message to improve it, thank you.
Save it as test.js

Copy code The code is as follows:

/**
* Data validation framework. When an error occurs in the id field check, a < span> element is added directly after the corresponding response to display the error message.
*
* @author wangzi6hao
* @version 2.1
* @description 2009-05-16
*/
var checkData = new function() {
var idExt="_wangzi6hao_Span";//Generate the id suffix of the span layer
/**
* Get the Chinese and English character length (Chinese is 2 characters)
*
* @param {}
* str
* @return The character length
*/
this.length = function(str) {
var p1 = new RegExp('%u..', 'g')
var p2 = new RegExp('%.', 'g')
return escape(str).replace(p1, '').replace(p2, '').length
}

/**
* Delete the corresponding id element
*/
this.remove = function(id) {
var idObject = document.getElementById(id);
if (idObject != null)
idObject.parentNode.removeChild(idObject);
}

/**
* Error message after the corresponding id
*
* @param id: The id element that needs to display the error message
* str: Display the error message
*/
this.appendError = function(id, str) {
this.remove(id idExt); // If the span element exists, delete this element first
var spanNew = document.createElement("span");// Create span
spanNew.id = id idExt;// Generate spanid
spanNew.style.color = "red";
spanNew .appendChild(document.createTextNode(str));//Add content to span
var inputId = document.getElementById(id);
inputId.parentNode.insertBefore(spanNew, inputId.nextSibling);//As needed Add span
}

/**
* @description to filter out all space characters after adding the element.
* @param str: The original string that needs to remove spaces
* @return Returns the string with spaces removed
*/
this.trimSpace = function(str) {
str = "";
while ((str.charAt(0) == ' ') || (str.charAt(0) == '???')
|| (escape(str.charAt(0 )) == '%u3000'))
str = str.substring(1, str.length);
while ((str.charAt(str.length - 1) == ' ')
|| (str.charAt(str.length - 1) == '???')
|| (escape(str.charAt(str.length - 1)) == '%u3000'))
str = str.substring(0, str.length - 1);
return str;
}

/**
* Filter the spaces at the beginning of the string and the spaces at the end of the string. Change multiple connected spaces in the middle of the text into one space
*
* @param {Object}
* inputString
*/
this.trim = function(inputString ) {
if (typeof inputString != "string") {
return inputString;
}
var retValue = inputString;
var ch = retValue.substring(0, 1);
while (ch == " ") {
// Check the space at the beginning of the string
retValue = retValue.substring(1, retValue.length);
ch = retValue.substring(0, 1);
}
ch = retValue.substring(retValue.length - 1, retValue.length);
while (ch == " ") {
// Check the end of the string Space
retValue = retValue.substring(0, retValue.length - 1);
ch = retValue.substring(retValue.length - 1, retValue.length);
}
while (retValue. indexOf(" ") != -1) {
// Change multiple connected spaces in the middle of the text into one space
retValue = retValue.substring(0, retValue.indexOf(" "))
retValue.substring(retValue.indexOf(" ") 1,
retValue.length);
}
return retValue;
}

/**
* Filter string, specify the filter content. If the content is empty, the default filter is '~!@#$%^&*()- ."
*
* @param {Object}
* str
* @param {Object}
* filterStr
*
* @return contains filter content, returns True, otherwise returns false;
*/
this.filterStr = function(str, filterString) {
filterString = filterString == "" ? "'~!@#$%^&*()- ."" : filterString
var ch;
var i;
var temp;
var error = false; // When illegal characters are included, return True
for (i = 0; i <= (filterString.length - 1); i ) {
ch = filterString.charAt(i);
temp = str.indexOf(ch);
if (temp != -1) {
error = true;
break ;
}
}
return error;
}

this.filterStrSpan = function(id, filterString) {
filterString = filterString == "" ? "'~ !@#$%^&*()- ."" : filterString
var val = document.getElementById(id);
if (this.filterStr(val.value, filterString)) {
val .select();
var str = "Cannot contain illegal characters" filterString;
this.appendError(id, str);
return false;
} else {
this.remove( id idExt);
return true;
}
}

/**
* Check if it is a URL
*
* @param {}
* str_url
* @return {Boolean} true: It is a URL, false: is not */
this.isURL = function(str_url) {// Verify url
var strRegex = "^((https|http|ftp|rtsp|mms)?://)"
"?(([0-9a-z_!~*'().&= $%-] : )?[0-9a-z_!~*'().&= $%-] @)?" // ftp user@
"(([0-9]{1,3}.) {3}[0-9]{1,3}" // URL in IP form - 199.194.52.184
"|" // Allow IP and DOMAIN (domain name)
"([0-9a-z_ !~*'()-] .)*" // Domain name - www.
"([0-9a-z][0-9a-z-]{0,61})?[0-9a- z]." // Second level domain name
"[a-z]{2,6})" // first level domain- .com or .museum
"(:[0-9]{1,4} )?" // port - :80
"((/?)|" // a slash isn't required if there is no file name
"(/[0-9a-z_!~*' ().;?:@&= $,%#-] ) /?)$";
var re = new RegExp(strRegex);
return re.test(str_url);
}

this.isURLSpan = function(id) {
var val = document.getElementById(id);
if (!this.isURL(val.value)) {
val.select( );
var str = "Link does not conform to the format;";
this.appendError(id, str);
return false;
} else {
this.remove(id idExt) ;
return true;
}
}

/**
* Check if it is an email
*
* @param {}
* str
* @return {Boolean} true: email, false: is notEmail;
*/
this.isEmail = function(str) {
var re = /^( [a-zA-Z0-9] [_|-|.]?)*[a-zA-Z0-9] @([a-zA-Z0-9] [_|-|.]?)*[ a-zA-Z0-9] .[a-zA-Z]{2,3}$/;
return re.test(str);
}

this.isEmailSpan = function (id) {
var val = document.getElementById(id);
if (!this.isEmail(val.value)) {
val.select();
var str = "Email Does not meet the format;";
this.appendError(id, str);
return false;
} else {
this.remove(id idExt);
return true;
}
}

/**
* Check if it is a number
*
* @param {}
* str
* @return {Boolean} true: number, false: is not Number;
*/
this.isNum = function(str) {
var re = /^[d] $/
return re. test(str);
}

this.isNumSpan = function(id) {
var val = document.getElementById(id);
if (!this.isNum(val.value)) {
val.select ();
var str = "Must be a number;";
this.appendError(id, str);
return false;
} else {
this.remove(id idExt) ;
return true;
}
}

/**
* Check whether the value is within the given range, if it is empty, no check is performed

*
* @param {}
* str_num
* @param {}
* small The value that should be greater than or equal to (when this value is empty, only check that it cannot be greater than the maximum value)
* @param {}
* big The value that should be less than or equal to (when this value is empty, only The check cannot be less than the minimum value)
*
* @return {Boolean} Less than the minimum value or greater than the maximum valueNumber returns false, otherwise returns true;
*/
this.isRangeNum = function(str_num, small, big) {
if ( !this.isNum(str_num)) // Check if it is a number
return false

if (small == "" && big == "")
throw str_num "No maximum or minimum is defined Worth the numbers!";

if (small != "") {
if (str_num < small)
return false;
}
if (big != "") {
if (str_num > big)
return false;
}
return true;

}

this.isRangeNumSpan = function(id, small, big) {
var val = document.getElementById(id);
if (!this.isRangeNum(val.value, small, big)) {
val.select();
var str = "";
if (small != "") {
str = "应该大于或者等于 " small;
}

if (big != "") {
str = " 应该小于或者等于 " big;
}
this.appendError(id, str);
return false;
} else {
this.remove(id idExt);
return true;
}
}

/**
* Check whether it is a qualified string (case-insensitive)

* is a string composed of a-z0-9_
*
* @param {}
* str Checked string
* @param {}
* idStr Cursor positioned field ID can only receive ID
* @return {Boolean} No "a-z0-9_" composition returns false, otherwise returns true;
*/
this.isLicit = function(str) {
var re = /^[_0-9a-zA-Z]*$/
return re.test(str);
}

this.isLicitSpan = function(id) {
var val = document.getElementById(id);
if (!this.isLicit(val.value)) {
val.select();
var str = "是由a-z0-9_组成的字符串(不区分大小写);";
this.appendError(id, str);
return false;
} else {
this.remove(id idExt);
return true;
}
}

/**
* Check whether two strings are equal
*
* @param {}
* str1 first string
* @param {}
* str2 second character String
* @return {Boolean} If the strings are not equal, return false, otherwise return true;
*/
this.isEquals = function(str1, str2) {
return str1 == str2;
}

this.isEqualsSpan = function(id, id1) {
var val = document.getElementById(id);
var val1 = document.getElementById(id1);
if (!this.isEquals(val.value, val1.value)) {
val.select();
var str = "二次输入内容必须一样;";
this.appendError(id, str);
return false;
} else {
this.remove(id idExt);
return true;
}
}

/**
* Check whether the string is within the given length range (Chinese characters are calculated as 2 bytes). If the character is empty, no check is performed

*
* @param {}
* str Checked characters
* @param {}
* lessLen The length that should be greater than or equal to
* @param {}
* moreLen The length that should be less than or equal to
*
* @return {Boolean} Less than the minimum length or greater than the maximum lengthNumber returns false;
*/
this.isRange = function(str, lessLen, moreLen) {
var strLen = this.length(str);

if (lessLen != "") {
if (strLen < lessLen)
return false;
}

if (moreLen != "") {
if (strLen > moreLen)
return false;
}

if (lessLen == "" && moreLen == "")
throw "没有定义最大最小长度!";
return true;
}

this.isRangeSpan = function(id, lessLen, moreLen) {
var val = document.getElementById(id);
if (!this.isRange(val.value, lessLen, moreLen)) {
var str = "长度";

if (lessLen != "")
str = "大于或者等于 " lessLen ";";

if (moreLen != "")
str = " 应该小于或者等于 " moreLen;

val.select();
this.appendError(id, str);
return false;
} else {
this.remove(id idExt);
return true;
}
}

/**
* Check whether the string is smaller than the given length range (Chinese characters are calculated as 2 bytes)

*
* @param {}
* str string
* @param {}
* lessLen less than or equal to the length
*
* @return {Boolean} less than the given length number returns false;
*/
this.isLess = function(str, lessLen) {
return this.isRange(str, lessLen, "");
}

this.isLessSpan = function(id, lessLen) {
var val = document.getElementById(id);
if (!this.isLess(val.value, lessLen)) {
var str = "长度大于或者等于 " lessLen;
val.select();
this.appendError(id, str);
return false;
} else {
this.remove(id idExt);
return true;
}
}

/**
* Check whether the string is larger than the given length range (Chinese characters are calculated as 2 bytes)

*
* @param {}
* str string
* @param {}
* moreLen less than or equal to the length
*
* @return {Boolean} greater than the given length number returns false;
*/
this.isMore = function(str, moreLen) {
return this.isRange(str, "", moreLen);
}

this.isMoreSpan = function(id, moreLen) {
var val = document.getElementById(id);
if (!this.isMore(val.value, moreLen)) {
var str = "长度应该小于或者等于 " moreLen;
val.select();
this.appendError(id, str);
return false;
} else {
this.remove(id idExt);
return true;
}
}

/**
* 检查字符不为空
*
* @param {}
* str
* @return {Boolean} Character is empty Return true, otherwise false;
*/
this.isEmpty = function(str) {
return str == "";
}

this.isEmptySpan = function(id) {
var val = document.getElementById(id);
if (this.isEmpty (val.value)) {
var str = "Null is not allowed;";
val.select();
this.appendError(id, str);
return false;
} else {
this.remove(id idExt);
return true;
}
}
}


The following is the specific test Page:
Copy code The code is as follows:


Webpage title


< script type="text/javascript">
function checkForm(){
var isPass = true;
//Filter string
if(!(checkData.isEmptySpan("filterStr") && checkData.filterStrSpan('filterStr','#$%$'))) {
isPass = false;
}

//Check url
if(!(checkData.isEmptySpan( "isURL") && checkData.isURLSpan('isURL')))
isPass = false;

//email
if(!(checkData.isEmptySpan("isEmail") && checkData.isEmailSpan ('isEmail')))
isPass = false;

//Number
if(!(checkData.isNumSpan('isNum')))
isPass = false;

//Number size
if(!(checkData.isEmptySpan("isRangeNum") && checkData.isNumSpan('isRangeNum') && checkData.isRangeNumSpan('isRangeNum',10,100)))
isPass = false ;

//Password (numbers, letters, underscores)
if(!(checkData.isLicitSpan('isLicit'))))
isPass = false;

//two Whether the fields are equal
if(!(checkData.isEmptySpan("isEquals") && checkData.isEqualsSpan('isEquals','isEquals1')))
isPass = false;

//Characters Length control
if(!(checkData.isRangeSpan('isRange',5,10)))
isPass = false;

//Shortest character control
if(!(checkData. isLessSpan('isLess',10)))
isPass = false;

//The longest character control
if(!(checkData.isEmptySpan("isMore") && checkData.isMoreSpan(' isMore',30)))
isPass = false;

//Empty control
if(!(checkData.isEmptySpan("isEmpty")))
isPass = false;
return isPass;
}































Character filtering: Link:
Email: Number:
Number range: a-zA-Z0-9_
Judge equality: < ;/td>
Length control: < ;/td>
Length is greater than control:
Length is less than control: Whether Empty:
< ;input type="submit" name="submit" value="Submit data">






Rendering:
js form validation function currently popular error message_javascript skills
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template