Bootstrap and validator using notes (JAVA SPRINGMVC implementation) _javascript tips

Source: Internet
Author: User
Tags format message valid email address

BootStrap is a powerful front frame that solves web problems in an elegant way. Recently using form validation for its development web site, a few experiences are as follows:

Note: This article draws on the blog Franson's article using Bootstrap Validator Remote Authentication Code experience sharing (recommended)

First, preparatory work

1. Your website environment must have the BootStrap, the Chinese net address: http://www.bootcss.com/

2. Download bootstrap Validator Related Materials, address: http://bv.doc.javake.cn/

Of course, if you do not want one to download to your project, you can introduce CDN,CDN can be used BootStrap official, Baidu can also search under the "BootStrap CDN", you must understand how to use. Here's My introduction code:

<!--new Bootstrap core CSS file--> <link rel= "stylesheet" href= "//cdn.bootcss.com/bootstrap/3.3.5/css/" Bootstrap.min.css "> <!--Optional bootstrap theme files (generally not introduced)--> <link rel=" stylesheet "href="//cdn.bootcss.com/" Bootstrap/3.3.5/css/bootstrap-theme.min.css "> <!--jquery file.
Be sure to introduce--> <script src= "//cdn.bootcss.com/jquery/1.11.3/jquery.min.js" before Bootstrap.min.js ></script> <!--the latest Bootstrap core JavaScript files--> <script src= "//cdn.bootcss.com/bootstrap/3.3.5/js/bootstrap.min.js" ></script> <!--Bootstrap Validator js file--> <script src= "//cdn.bootcss.com/bootstrap-validator/ 0.5.3/js/bootstrapvalidator.min.js "></script> <!--Bootstrap Validator style file--> <link href="// Cdn.bootcss.com/bootstrap-validator/0.5.3/css/bootstrapvalidator.min.css "rel=" stylesheet "> <!--bootstrap Validator Chinese Language Pack--> <script src= "//cdn.bootcss.com/bootstrap-validator/0.5.3/js/language/zh_cn.min.js" > </script>

Second, preliminary application.

Here is a direct reference to the official example of Bootstrap Validator, first look at the HTML code:

<form class= "Form-horizontal" >
<div class= "Form-group" >
<label class= "Col-lg-3" Control-label ">Username</label>
<div class=" col-lg-9 ">
<input type=" text "class=" Form-control "name=" username "/>
</div>
</div>
<div class=" Form-group ">
<label class= "col-lg-3 control-label" >email address</label> <div class=
"col-lg-9" >
<input type= "text" class= "Form-control" name= "email"/>
</div>
</div>
</form >

A very common bootstrap page code, a form, which is the user name, email address two input

Bootstrap validation is checked against the name value of the form control, and the following is the JS code:

<script> $ (document). Ready (function () {$ ('. Registerform '). Bootstrapvalidator ({message: ' Valid ',//validation error information Feedbackicons: {//validation when the icon displayed valid: ' Glyphicon glyphicon-ok ',//Correct icon invalid: ' Glyphicon Glyphicon-remo ve ',//Error icon validating: ' Glyphicon glyphicon-refresh '//Updating Icon}, fields: {//To verify which fields Username: {//The name attribute of input in the form corresponds to MES Sage: ' The username is not valid ',//validation error information, of course, here is the validators in Chinese: {notempty: {//non-NULL judgment message: ' The username is requ  Ired and cannot be empty '//Validation error information,}, Stringlength: {//length judged Min:6,//must not be less than max:30,//No more than message: ' The username must Be more than 6 and less than characters long '///validation error information, RegExp: {//Regular expression judgment regexp:/^[a-za-z0-9_]+$/,//expression content M Essage: ' The username can only consist of alphabetical, number and underscore '//validation error information,}}, email: {validators: {n Otempty: {message: ' The email is required and cannot being empty '}, EmailAddress: {//is not the correct email format message: ' The input is
Not a valid email address '}}}
}
});
}); </script>

BootStrap Validator has already defined a number of authentication methods, each of which uses the following: http://bv.doc.javake.cn/validators/

Several of them are commonly used, mention, actually a look on understand, very good understanding:

Third, advanced application

If you do not want to use the default template, you can use the following methods to do some custom validation

Callback Way, API address: http://bv.doc.javake.cn/validators/callback/

The callback method allows you to use custom functions for judgment, as shown in the following example

HTML (content is the result of the display input operation)

<form id= "Captchaform" class= "Form-horizontal" >
<div class= "Form-group" >
<label class= " Col-lg-3 Control-label "id=" captchaoperation "></label>
<div class=" col-lg-2 ">
<input Type= "text" class= "Form-control" name= "Captcha"/>
</div>
</div>
</form>

Look at JS.

 <script> $ (document). Ready (function () {///randomly take a number function Min,max in the middle of Randomnumber (
Min, max) {return Math.floor (Math.random () * (Max-min + 1) + min); Generates a random two-digit addition of the text display, which is displayed in the Capchaoperation $ (' #captchaOperation '). HTML ([Randomnumber (1, m), ' + ', randomnumber (1, 200   
), ' = '].join (') '); $ (' #captchaForm '). Bootstrapvalidator ({//verify Feedbackicons: {valid: ' Glyphicon glyphicon-ok ', invalid: ' Glyphicon Glyphicon-remove ', validating: ' Glyphicon glyphicon-refresh '}, fields: {captcha: {validators: {callback: {//callback side Message: ' Wrong answer ', callback:function (value, validator) {//You can implement custom functionality here//determine the numbers which, are Gener  Ated in Captchaoperation//This is the value entered in input var items = $ (' #captchaOperation '). html (). Split ("), sum =
parseint (Items[0]) + parseint (items[2));
return value = = SUM;
}
}
}
}
}
});
}); </script> 

So when the default way does not meet your requirements can be used callback way, the realization of their own functions used to complete special judgments, such as to determine whether the Chinese identity card number is correct ...

Four, asynchronous verification

The most common application is to verify that the username is registered, and look at the code in my program:

Html

<form class= "Form-horizontal" >
<div class= "Form-group has-feedback has-error" >
<label for= " LoginName "class=" col-sm-3 Control-label "> Username:</label> <div class=
" col-sm-5 ">
<div Class = "Input-group" >
<input type= "text" class= "Form-control" id= "LoginName" "Name=" LoginName "placeholder=" Please enter your login username ">
<span class=" Input-group-addon "> </span>
</div>
</div>
</div>
</form>

Js

<script>
$ (function () {
$ (' form '). Bootstrapvalidator ({message
: ' This value isn't valid ',
Feedbackicons: {
valid: ' Glyphicon glyphicon-ok ',
invalid: ' Glyphicon glyphicon-remove ',
validating: ' Glyphicon Glyphicon-refresh '},
fields: {
loginName: {message
: ' User name validation failed ',
validators: {
Notempty: {message: ' User name cannot be empty '},
stringlength: {min:6,max:18,message: ' username must be between 6 and 18 bits '},
regexp: {regexp: /^[a-za-z0-9_]+$/,message: ' username can only contain uppercase, lowercase, digits, and underscore '},
remote: {message
: ' Username already exists ',
URL: '/ajax/ Checknewuser ',//action address, here I tried, should be unable to join EL, but see online can add <%=%> output a value, I did not succeed in the experiment, do not know why
data:{//Pass Parameters
Username:function () {return $ ("#loginName"). Val ()},//username parameter name without quotes, if you want to pass in the value of a particular control must join a function, so that you can pass the value into, do not know why ...
delay:2000,//Each character, the AJAX request, server pressure is too large, set 2 seconds to send an AJAX (default input one character, submit once, server pressure too Large)
type: ' POST '// Request Mode
}
}}}); </script>

Action with SPRINGMVC implementation

Package Com.aocshallo.actions.ajax;
Import java.io.IOException;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;
Import javax.servlet.http.HttpSession;
Import Org.json.JSONObject;
Import Org.springframework.stereotype.Controller;
Import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping ("/ajax") public class Ajaxaction extends Baseaction {public ajaxaction () {//TODO Auto-gener Ated constructor stub} @RequestMapping ("/checknewuser") public void Checknewuser (HttpSession session, HttpServletRequest request,httpservletresponse response) throws ioexception{//..... This is your judgment logic Boolean ret = true; 
This is the final return value//below is the response setting Response.setcontenttype ("Text/xml;charset=utf-8"); 
Response.setheader ("Cache-control", "No-cache"); 
try {//This is a way to output as a JSON string, the result should be a JSON string, the property name must be valid, the value is True or false jsonobject Jsobjcet = new Jsonobject ();
Jsobjcet.put ("valid", ret); 
Response.getwriter (). Write (jsobjcet.tostring ()); System.out.prinTLN (Jsobjcet.tostring ()); 
catch (IOException e) {e.printstacktrace (); } 
}
}

The final output of your action must be text in the following form:

{"Valid": false}//is illegal, validation does not pass
{"valid": true}//representation is valid, validation passes

So we use Jsonobject as output.

The above is a small set to introduce the Bootstrap-validator use Records (JAVA SPRINGMVC implementation), I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.