HI WELCOME TO SIRIS

Create simple forms with validation in React.js

Leave a Comment

Introduction

This is the 4th article of the series "React.js with asp.net MVC application".
In the previous post, I have shown you Server-side paging and sorting in React JS Today I am going to show you, how to create simple forms with validation and save data to the database using React.js, ASP.NET MVC and entity framework.

In this series, we have already seen 3 article and all about create react component for show data from a database. Now we will see how to create a form with validation for save data to the database. As this is our first article about creating a form for save data, we will start with a very simple contact us form with 3 input fields (Full Name, Email and Message).

Just follow the following steps in order to create simple forms with validation in React.js

Here In this article, I have used Visual Studio 2013 

Step - 1: Create New Project.

Go to File > New > Project > ASP.NET  Web Application (under web) > Entry Application Name > Click OK > Select Empty template > Checked MVC (under "Add folders and core references for" option) > OK

Step-2: Add a Database.

Go to Solution Explorer > Right Click on App_Data folder > Add > New item > Select SQL Server Database Under Data > Enter Database name > Add.

Step-3: Create a table for store data.

Open Database > Right Click on Table > Add New Table > Add Columns > Save > Enter table name > Ok.

In this example, I have used a table as below


ContactsData Table 


Step-4: Add Entity Data Model.

Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select ADO.net Entity Data Model under data > Enter model name > Add.
A popup window will come (Entity Data Model Wizard) > Select Generate from database > Next >
Chose your data connection > select your database > next > Select tables > enter Model Namespace > Finish.

Step-5: Add a javascript file for creating React components.

Here I have added a javascript file (ContactForm.js) in the "Scripts" folder for creating reusable react components.

Right click on your "Scripts" folder > Add > New Item > select "javascript" file > Enter name (here "ContactForm.js")> Ok.
Write following code
  1. // Here we will create react component for generate form with validation
  2.  
  3. //React component for input component
  4. var MyInput = React.createClass({
  5. //onchange event
  6. handleChange: function (e) {
  7. this.props.onChange(e.target.value);
  8. var isValidField = this.isValid(e.target);
  9. },
  10. //validation function
  11. isValid: function (input) {
  12. //check required field
  13. if (input.getAttribute('required') != null && input.value ==="") {
  14. input.classList.add('error'); //add class error
  15. input.nextSibling.textContent = this.props.messageRequired; // show error message
  16. return false;
  17. }
  18. else {
  19. input.classList.remove('error');
  20. input.nextSibling.textContent = "";
  21. }
  22. //check data type // here I will show you email validation // we can add more and will later
  23. if (input.getAttribute('type') == "email" && input.value != "") {
  24. if (!this.validateEmail(input.value)) {
  25. input.classList.add('error');
  26. input.nextSibling.textContent = this.props.messageEmail;
  27. return false;
  28. }
  29. else {
  30. input.classList.remove('error');
  31. input.nextSibling.textContent = "";
  32. }
  33. }
  34. return true;
  35. },
  36. //email validation function
  37. validateEmail: function (value) {
  38. var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  39. return re.test(value);
  40. },
  41. componentDidMount: function () {
  42. if (this.props.onComponentMounted) {
  43. this.props.onComponentMounted(this); //register this input in the form
  44. }
  45. },
  46. //render
  47. render: function () {
  48. var inputField;
  49. if (this.props.type == 'textarea') {
  50. inputField = <textarea value={this.props.value} ref={this.props.name} name={this.props.name}
  51. className='form-control' required={this.props.isrequired} onChange={this.handleChange} />
  52. }
  53. else {
  54. inputField = <input type={this.props.type} value={this.props.value} ref={this.props.name} name={this.props.name}
  55. className='form-control' required={this.props.isrequired} onChange={this.handleChange} />
  56. }
  57. return (
  58. <div className="form-group">
  59. <label htmlFor={this.props.htmlFor}>{this.props.label}:</label>
  60. {inputField}
  61. <span className="error"></span>
  62. </div>
  63. );
  64. }
  65. });
  66. //React component for generate form
  67.  
  68. var ContactForm = React.createClass({
  69. //get initial state enent
  70. getInitialState : function(){
  71. return {
  72. Fullname : '',
  73. Email:'',
  74. Message : '',
  75. Fields : [],
  76. ServerMessage : ''
  77. }
  78. },
  79. // submit function
  80. handleSubmit : function(e){
  81. e.preventDefault();
  82. //Validate entire form here
  83. var validForm = true;
  84. this.state.Fields.forEach(function(field){
  85. if (typeof field.isValid === "function") {
  86. var validField = field.isValid(field.refs[field.props.name]);
  87. validForm = validForm && validField;
  88. }
  89. });
  90. //after validation complete post to server
  91. if (validForm) {
  92. var d = {
  93. Fullname: this.state.Fullname,
  94. Email : this.state.Email,
  95. Message : this.state.Message
  96. }
  97.  
  98. $.ajax({
  99. type:"POST",
  100. url : this.props.urlPost,
  101. data : d,
  102. success: function(data){
  103. //Will clear form here
  104. this.setState({
  105. Fullname : '',
  106. Email : '',
  107. Message : '',
  108. ServerMessage: data.message
  109. });
  110. }.bind(this),
  111. error : function(e){
  112. console.log(e);
  113. alert('Error! Please try again');
  114. }
  115. });
  116. }
  117. },
  118. //handle change full name
  119. onChangeFullname : function(value){
  120. this.setState({
  121. Fullname : value
  122. });
  123. },
  124. //handle chnage email
  125. onChangeEmail : function(value){
  126. this.setState({
  127. Email : value
  128. });
  129. },
  130. //handle change message
  131. onChangeMessage : function(value){
  132. this.setState({
  133. Message : value
  134. });
  135. },
  136. //register input controls
  137. register : function(field){
  138. var s = this.state.Fields;
  139. s.push(field);
  140. this.setState({
  141. Fields : s
  142. })
  143. },
  144. //render
  145. render : function(){
  146. //Render form
  147. return(
  148. <form name="contactForm" noValidate onSubmit={this.handleSubmit}>
  149. <MyInput type={'text'} value={this.state.Fullname} label={'Full Name'} name={'Fullname'} htmlFor={'Fullname'} isrequired={true}
  150. onChange={this.onChangeFullname} onComponentMounted={this.register} messageRequired={'FullName required'} />
  151. <MyInput type={'email'} value={this.state.Email} label={'Email'} name={'Email'} htmlFor={'Email'} isrequired={false}
  152. onChange={this.onChangeEmail} onComponentMounted={this.register} messageRequired={'Invalid Email'} />
  153. <MyInput type={'textarea'} value={this.state.Message} label={'Message'} name={'Message'} htmlFor={'Message'} isrequired={true}
  154. onChange={this.onChangeMessage} onComponentMounted={this.register} messageRequired={'Message required'} />
  155. <button type="submit" className="btn btn-default">Submit</button>
  156. <p className="servermessage">{this.state.ServerMessage}</p>
  157. </form>
  158. );
  159. }
  160. });
  161.  
  162. //Render react component into the page
  163. ReactDOM.render(<ContactForm urlPost="/home/SaveContactData" />, document.getElementById('contactFormArea'));
If you see, here I have created two React components named MyInput (for generating input type form components with validation function), and ContactForm (for generating form element).

Step-6: Create an MVC Controller.

Go to Solution Explorer > Right Click on Controllers folder form Solution Explorer > Add > Controller > Enter Controller name > Select Templete "empty MVC Controller"> Add.

Here I have created a controller named "HomeController"

Step-7: Add new action into your controller for getting the view, where we will show our ContactForm component (react). 

Here I have added "Index" Action into "Home" Controller. Please write this following code
  1. public ActionResult Index()
  2. {
  3. return View();
  4. }

Step-8: Add view for your Action and design.

Right Click on Action Method (here right click on Index action) > Add View... > Enter View Name > Select View Engine (Razor) > Add.
HTML Code 
  1. @{
  2. ViewBag.Title = "Create simple form with validation in React.js";
  3. }
  4.  
  5. <div class="container">
  6. <h2>Create simple form with validation in React.js</h2>
  7. <div id="contactFormArea">
  8.  
  9. </div>
  10. </div>
  11.  
  12. @* Load css and js library *@
  13.  
  14. @* Bootstrap css *@
  15. <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
  16. @* jquery library *@
  17. <script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
  18. @* React library *@
  19. <script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.6/react.js"></script>
  20. <script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.6/react-dom.js"></script>
  21. <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>
  22. @* our react component *@
  23. <script src="~/Scripts/ContactForm.js" type="text/babel"></script>
  24.  
  25. <style type="text/css">
  26. .form-control.error{
  27. border-color:red;
  28. background-color:#FFF6F6;
  29. }
  30. span.error{
  31. color:red;
  32. }
  33. .servermessage{
  34. font-size:32px;
  35. margin-top:20px;
  36. }
  37. </style>

Step-9: Add another action to your controller for save  data to the database.

Here I have created "SaveContactData" Action for saving data. Please write this following code
  1. [HttpPost]
  2. public JsonResult SaveContactData(ContactsData contact)
  3. {
  4. bool status = false;
  5. string message = "";
  6. if (ModelState.IsValid)
  7. {
  8. using (MyDatabaseEntities dc = new MyDatabaseEntities())
  9. {
  10. dc.ContactsDatas.Add(contact);
  11. dc.SaveChanges();
  12. status = true;
  13. message = "Thank you for submit your query";
  14. }
  15. }
  16. else
  17. {
  18. message = "Failed! Please try again";
  19. }
  20. return new JsonResult { Data = new { status = status, message = message } };
  21. }

Step-10: Run Application.

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.