search
HomeWeb Front-endJS TutorialjQuery form validation plug-in formValidator (improved version)_jquery

Usage of enumeration objects:

Copy code The code is as follows:

//Various verification methods Supported tag types
sustainType: function (elem, setting) {
var srcTag = elem.tagName;
var stype = elem.type;
switch (setting.validatetype) {
case _validTypeEnum.InitValidator:
return true;
case _validTypeEnum.InputValidator:
if (srcTag == _validTagEnum.INPUT || srcTag == _validTagEnum.TEXTAREA || srcTag == _validTagEnum.SELECT) {
return true;
} else {
return false;
}
case _validTypeEnum.CompareValidator:
if (srcTag == _validTagEnum.INPUT || srcTag == _validTagEnum.TEXTAREA) {
if (stype == _validTagTypeEnum.checkbox || stype == _validTagTypeEnum.radio) {
return false;
} else {
return true;
}
}
return false ;
case _validTypeEnum.AjaxValidator:
if (stype == _validTagTypeEnum.text || stype == _validTagTypeEnum.textarea || stype == _validTagTypeEnum.file || stype == _validTagTypeEnum.password || stype == _validTagTypeEnum .select_one) {
return true;
} else {
return false;
}
case _validTypeEnum.RegexValidator:
if (srcTag == _validTagEnum.INPUT || srcTag == _validTagEnum.TEXTAREA) {
if (stype == _validTagTypeEnum.checkbox || stype == _validTagTypeEnum.radio) {
return false;
} else {
return true;
}
}
return false;
case _validTypeEnum.FunctionValidator:
return true;
}
}

Copy code The code is as follows:

//Get the length of the specified string
getLength: function (jqObj) {
var elem = _GetDomObj( jqObj);
var sType = elem.type;
var len = 0;
switch (sType) {
case _validTagTypeEnum.text:
case _validTagTypeEnum.hidden:
case _validTagTypeEnum .password:
case _validTagTypeEnum.textarea:
case _validTagTypeEnum.file:
var val = jqObj.val();
var initConfig = $.formValidator.getInitConfig(elem.settings[0]. validatorgroup);
len = initConfig.wideword ? String.getCharLength(val) : val.length;
break;
case _validTagTypeEnum.checkbox:
case _validTagTypeEnum.radio:
len = $ ("input[type='" sType "'][name='" jqObj.attr("name") "']:checked").length;
break;
case _validTagTypeEnum.select_one:
case _validTagTypeEnum.select_multiple:
len = jqObj.children(":selected").length;
break;
}
return len;
}

2. In the original version, the ID of the verification label is passed between each method instead of the object of the verification label. This avoids the need to obtain the object of the verification label based on the ID in each method and improves the code execution speed and performance. .
3. In the original version, the prompt styles for verification success, errors, etc. have limited style names in the plug-in. For example, the error prompt style name is: onError. This will make the artist need to care about the plug-in when using this plug-in. The name of each prompt style in the prompt, and also to avoid duplication or conflict of styles, which is very unpleasant to use. A truly good plug-in should completely separate js and styles (which need to be set by the user) - this is similar to 'loose coupling' in programming, but only in this way can js and styles be dependent on each other and better adapt to the needs of users ! So, I allowed users to configure each prompt style in the plug-in (as an attribute of the parameter object of the method). The main code is as follows:
Copy code The code is as follows:

//Tip style enumeration
var _tipCssEnum =
{
//(ajax) loading processing
loadCss: "loadCss",
//When getting focus Style
focusCss: "focusCss",
//Prompt [for empty prompt] ---If this is not set, use errorCss
noticeCss: "noticeCss",
//Failed or error [for format error, regular expression verification]---must set
errorCss: "errorCss",
//Success---must set
successCss: "successCss",
//Default state---must be set
defaultCss: "defaultCss"
};
initConfig: function (controlOptions) {
var settings =
{
debug: false,/ /Whether it is debugging mode
validatorgroup: "1",//Validation group
alertmessage: false,//Whether the verification prompt pops up directly
validobjectids: "",//Validation object collection
focusvalid: false,
onsuccess: function () { return true; }, //Processing method after successful verification, return true|false (can add form verification or prevent form submission, etc.)
onerror: function () { } ,
filterInputStrFun: function (str) { return FilterInputOper.FilterInputStr(str); }, //Method to filter input string [can be set]
isformpost: false, //Whether it is a form submission (default: false ——Non-form submission, usually ajax submission, true——form submission)
submitonce: false,//Whether the form is submitted immediately after verification is passed
submitbutton: null,//Submit button id or object
getformdata: null, //function (formdata) { } (after verification is passed) get the input form value - this method will only be called when isformpost=false
//Verification prompt display settings (default: default According to settings)
tipshow: "default",
formid: "", //Verify the id or object of the form
tidymode: false, //Lite mode
errorfocus: true,
wideword : true,
//Validation prompt style setting (global)
tipcss:
{
//(ajax) loading processing
loadCss: "",
//When getting focus Style
focusCss: "",
//Prompt
noticeCss: "",
//Success
successCss: "",
//Failure
errorCss: " ",
//Default state
defaultCss: ""
}
};
controlOptions = controlOptions || {};
controlOptions.tipcss = controlOptions.tipcss || {} ;
//Merge the entire configuration (deep copy)
$.extend(true, settings, controlOptions);
if (!settings.isformpost) {
if (!settings.submitbutton) {
alert("submitbutton cannot be empty! ");
return;
}
_GetJqObj(settings.submitbutton).click(function () {
var pageIsValid = $.formValidator.pageIsValid(settings.validatorgroup);
if ( pageIsValid && _IsFunction(settings.getformdata)) {
var formData = _GetFormData(settings.filterInputStrFun);
settings.getformdata(formData);
}
});
}
settings.tipshow = settings.tipshow || "default";
//If it is streamlined mode, when an error occurs, the first error control will not get focus
if (settings.tidymode) {
settings.errorfocus = false;
}
if (settings.formid) {
_GetNodeById(settings.formid).submit(function () {
//If it is not a form submission, block the form Submit
return settings.isformpost ? $.formValidator.pageIsValid(settings.validatorgroup) : false;
});
}
if (_jQuery_formValidator_initConfig_Array == null) {
_jQuery_formValidator_initConfig_Array = new Array ();
}
_jQuery_formValidator_initConfig_Array.push(settings);
}
//Set tip information
setTipState: function (elem, showCssEnum, showmsg) {
var setting0 = elem .settings[0];
var initConfig = $.formValidator.getInitConfig(setting0.validatorgroup);
if (initConfig.alertmessage && showmsg) {
alert(showmsg);
return
}
var jq_tipObj = setting0.tipJqObj;
var tip_IsNull = Object.isNull(jq_tipObj);
if (!tip_IsNull) {
showmsg = showmsg || "";
if (initConfig .tidymode) {
//Save prompt information
elem.Tooltip = showmsg;
if (showCssEnum != _tipCssEnum.errorCss && showCssEnum != _tipCssEnum.noticeCss)
jq_tipObj.hide();
}
jq_tipObj.removeClass();
//Set tip style
var showClass = setting0.tipcss[showCssEnum];
//If noticeCss is not set, use errorCss
if (String.isNullOrEmpty(showClass) && showCssEnum == _tipCssEnum.noticeCss) {
showCssEnum = _tipCssEnum.errorCss;
showClass = setting0.tipcss[showCssEnum];
}
if (!String.isNullOrEmpty (showClass)) {
//Save the style of the current tip label display (enumeration value)
elem.showcssenum = showCssEnum;
jq_tipObj.addClass(showClass);
}
jq_tipObj. html(showmsg);
}
}

4. Added some properties to the initConfig configuration object to meet more needs and enhance functionality and ease of use, such as:
filterInputStrFun: function (str) { return FilterInputOper.FilterInputStr(str); } , //Method for filtering the input string [can be set] - to meet the need for filtering the input string
Isformpost: false, //Whether it is a form submission (default: false - non-form submission, usually ajax Submit, true - form submission) - to meet the needs of ajax submission and form submission
Getformdata: null, //function (formdata) { } (after verification) get the input form value - only isformpost=false
Tipshow: "default", //Verification prompt display settings (default: default according to settings) - Set the verification prompt label object search method, based on Id or custom jQuery search (find) method.
 
The usage of the plug-in is as follows:
Copy the code The code is as follows:




您好,欢迎来到山水檀溪!
退出











jQuery form validation plug-in formValidator (improved version)_jquery







添加栋号 >> 第一步








山水檀溪















待售

期房

现房

尾房

售完











  • 普通住宅


  • 单身公寓


  • 复式


  • 别墅


  • 厂房


  • 写字楼


  • 商铺


  • 经济适用房














































  id="btnCancel_Step1" type="button" class="jy_fcadminbottom02" value="取 消" />



















The above is my introduction to the main improvements of this plug-in. The overall plug-in still maintains the structure and ideas of the original version. What it does is to make the plug-in more readable and usable. I share it today in the hope that there will be More friends can help test it and put forward some opinions or ideas to make this form validation plug-in formValidator more usable (continuous improvement can make it better, and improvement is inseparable from everyone's suggestions)!
Supplement: Need to solve the improved function - verification can support free combination, such as: phone and mobile phone only need to verify one of them to pass. I have tried to achieve this myself, but the effect is not ideal, and I did not think of a better one. Solution, I hope you can help consider it!
Plug-in and Demo download: FromVaild
Statement
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
Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor