Form data verification Method (ii)--asp. NET background verification

Source: Internet
Author: User


Yesterday, I wrote about how to quickly implement the form data validation method in the foreground, today, then yesterday, the background of the implementation of data validation methods recorded. First of all, I'm using ASP. So the background verification method is also based on. NET MVC.



Well, gossip, I'm back to the chase.



Background implementation of form data validation method is also quite simple, the following see I step-by-step to do ha. (in order to simply explain how forms are validated, and to reduce other unnecessary content, I'm not involved in the database.) )



1. Create a new. NET MVC application



This step is not detailed today, there is time to write an article on how to create a new project and the implementation of simple additions and deletions of the blog, to consolidate their own, by the way to help and I like Montion chicken. To build the application, my name is FormCheck:







2. New User Information field Entity Data Class User816.cs



(The name of the people do not struggle with him, because I do not use the hot code just written, but the cold code written on August 16, because the evening time is limited, do not re-write)



As shown, I create a new User816.cs entity class in the Models folder, with the following code:


namespace FormCheck.Models
{
    public class User816
    {

        public string userName { get; set; }

        public string passWord { get; set; }

        public string eMail { get; set; }
             
    }
} 




Here we write three attributes, respectively, user name, password and mailbox, and the following will add a checksum method to these data.



The main additions [Required], [Stringlength], [regularexpression] Three bar, because these three are the most commonly used.



(1) Required



First look at the definition of this method:





This code only need to see can understand the Chinese character, yes, that is the "specified data field value is required", OK now we know what this means, then the question is, how does this thing use? See below:


 [Required (errormessage ="* required fields ")]   Public string Get set; }




Wrap the required in brackets above the attributes that need to be validated, and then add the error message. How, is not very simple, haha.



(2) Stringlength



This is the same, take a look at the meaning and usage of this thing, just a stroke of it:







Use the following:


[Stringlength (5, errormessage ="* exceeds the length of "publicstring  getset; }




The first parameter "5" above refers to the maximum length of the string, of course, here is not only set the maximum length, you can also set the minimum length, more than that, there are many other uses, here I do not elaborate, the specific need to use the students can search for information on the Internet.



(3) RegularExpression



That's a good one. Verify the regular expression:







Use the following:


[RegularExpression(@"^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a -zA-Z0-9]{2,6}$", ErrorMessage = "*Mailbox format error")] //Regular expression
   Public string eMail { get; set; } 




As for these verification methods, let's take a look at the actual usage.



3. Validating data



(1) Add the desired validation to the corresponding attribute:



The code looks like this:


Namespace FormCheck.Models
{
     Public class User816
     {
         [StringLength(5,ErrorMessage ="*more than length")
         [Required]
         Public string userName { get; set; }

       
         [Required(ErrorMessage ="*Required")]
         [Range(100,1000000,ErrorMessage ="*number size is out of range")]
         Public string passWord { get; set; }

         [Required]
         [RegularExpression(@"^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a -zA-Z0-9]{2,6}$", ErrorMessage = "*Mailbox format error")] //Regular expression
         Public string eMail { get; set; }
             
     }
} 




(2) Reference User816.cs on the front page



First, create a new method in HomeController, named GetInfo (), add the corresponding view, and then reference the User816:













(3) Create a new form



The code is as follows:


<div>
     @using (Html.BeginForm("GetInfoFunc", "Home", FormMethod.Post))
     {
         @Html.ValidationSummary(true)
         <label class="btn-default">name</label>
         @Html.TextBoxFor(model => model.userName);
         @Html.ValidationMessageFor(model => model.userName)
         <br>
         <label class="btn-default">password</label>
         @Html.TextBoxFor(model => model.passWord);
         @Html.ValidationMessageFor(model => model.passWord)
         <br>
         <label class="btn-default">mailbox</label>
         @Html.TextBoxFor(model => model.eMail);
         @Html.ValidationMessageFor(model => model.eMail)
         <button class="btn-info" id="submit">submit</button>

     }
</div> 





Actually only need these three steps already can see the effect, but in order to guarantee a form to submit the demo completeness, I will make up the fourth step again, haha.



(4) Reception submission data, backstage reception



Ajax way to submit a form:


<script type="text/javascript">
    $(function () {
        $("#submit").click(function () {
            var userName = $("#userName").val();
            var passWord = $("#passWord").val();
            var eMail = $("#eMail").val();
            $.ajax({
                url: "@Url.Action("GetInfoFunc", "Home")",
                type: "post",
                data: {
                    userName: userName,
                    passWord: passWord,
                    eMail: eMail
                },
                success: function (data) {
                    alert(data);
                }
            });
        });
    });

</script> 




Background creation Controller GETINFOFUNC () receives data:


[HttpPost]
 public ActionResult GetInfoFunc()
 {
            string userName = Request["userName"];
            string passWord = Request["passWord"];
            string eMail = Request["eMail"];
            return Content(userName + "," + passWord + "," + eMail);
 } 




4. View Results










The effect here is similar to the way I wrote the front-end JS check yesterday, and it's very simple.





Well, today is written here, good study, day up, ah haha haha ha!



My email:3074596466@qq.com.



  


Related Article

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.