Sitecore WFFM-Webforms customize html structure - sitecore8

I am Using WFFM with Sitecore-8.2-Update 4 Version. So i have a requirement to change HTML structure of WFFM webforms.
Let me share my case.
We have Name Section that contains first name and last name.
IN WFFM form designer i have created like below
Then the Html is generated like below by WFFM.
<div class="required-field form-group">
<input id="wffm26cf3ccb39024ed0974e0f60d9292156_Sections_0__Fields_0__Id" name="wffm26cf3ccb39024ed0974e0f60d9292156.Sections[0].Fields[0].Id" type="hidden" value="{6DAF46AC-CEE6-4CB2-9391-40ACC39CCE74}" />
<label class="control-label" for="wffm26cf3ccb39024ed0974e0f60d9292156_Sections_0__Fields_0__Value">LastName</label>
<input class=" form-control text-box single-line" data-val="true" data-val-length="The LastName field must be a string with a minimum length of 0 and a maximum length of 256." data-val-length-max="256" data-val-required="This field is required." data-val-required-tracking="{7E86B2F5-ACEC-4C60-8922-4EB5AE5D9874}" id="wffm26cf3ccb39024ed0974e0f60d9292156_Sections_0__Fields_0__Value" name="wffm26cf3ccb39024ed0974e0f60d9292156.Sections[0].Fields[0].Value" placeholder="" style="" type="text" value="" /><span class="field-validation-valid help-block" data-valmsg-for="wffm26cf3ccb39024ed0974e0f60d9292156.Sections[0].Fields[0].Value" data-valmsg-replace="true">
</span>
</div>
<div class="required-field form-group">
<input id="wffm26cf3ccb39024ed0974e0f60d9292156_Sections_0__Fields_1__Id" name="wffm26cf3ccb39024ed0974e0f60d9292156.Sections[0].Fields[1].Id" type="hidden" value="{FF409749-4574-4D8C-971D-1A2D66B82FDA}" />
<label class="control-label" for="wffm26cf3ccb39024ed0974e0f60d9292156_Sections_0__Fields_1__Value">FirstName</label>
<input class=" form-control text-box single-line" data-val="true" data-val-length="The FirstName field must be a string with a minimum length of 0 and a maximum length of 256." data-val-length-max="256" data-val-required="This field is required." data-val-required-tracking="{7E86B2F5-ACEC-4C60-8922-4EB5AE5D9874}" id="wffm26cf3ccb39024ed0974e0f60d9292156_Sections_0__Fields_1__Value" name="wffm26cf3ccb39024ed0974e0f60d9292156.Sections[0].Fields[1].Value" placeholder="" style="" type="text" value="" /><span class="field-validation-valid help-block" data-valmsg-for="wffm26cf3ccb39024ed0974e0f60d9292156.Sections[0].Fields[1].Value" data-valmsg-replace="true">
</span>
</div>
But I need a Html like below one
<div class="required-field form-group has-feedback">
<span>
<input class=" form-control text-box single-line" data-val="true" data-val-length="The First field must be a string with a minimum length of 0 and a maximum length of 256." data-val-length-max="256" data-val-required="This field is required." data-val-required-tracking="{7E86B2F5-ACEC-4C60-8922-4EB5AE5D9874}" id="wffm26cf3ccb39024ed0974e0f60d9292156_Sections_0__Fields_1__Value" name="wffm26cf3ccb39024ed0974e0f60d9292156.Sections[0].Fields[1].Value" placeholder="" style="" type="text" value="">
<input id="wffm26cf3ccb39024ed0974e0f60d9292156_Sections_0__Fields_1__Id" name="wffm26cf3ccb39024ed0974e0f60d9292156.Sections[0].Fields[1].Id" type="hidden" value="{FF409749-4574-4D8C-971D-1A2D66B82FDA}">
<label class="control-label" for="wffm26cf3ccb39024ed0974e0f60d9292156_Sections_0__Fields_1__Value">First</label>
<span class="field-validation-valid help-block" data-valmsg-for="wffm26cf3ccb39024ed0974e0f60d9292156.Sections[0].Fields[1].Value" data-valmsg-replace="true">
</span>
</span>
<span>
<input class=" form-control text-box single-line" data-val="true" data-val-length="The Last field must be a string with a minimum length of 0 and a maximum length of 256." data-val-length-max="256" data-val-required="This field is required." data-val-required-tracking="{7E86B2F5-ACEC-4C60-8922-4EB5AE5D9874}" id="wffm26cf3ccb39024ed0974e0f60d9292156_Sections_0__Fields_0__Value" name="wffm26cf3ccb39024ed0974e0f60d9292156.Sections[0].Fields[0].Value" placeholder="" style="" type="text" value="">
<input id="wffm26cf3ccb39024ed0974e0f60d9292156_Sections_0__Fields_0__Id" name="wffm26cf3ccb39024ed0974e0f60d9292156.Sections[0].Fields[0].Id" type="hidden" value="{6DAF46AC-CEE6-4CB2-9391-40ACC39CCE74}">
<label class="control-label" for="wffm26cf3ccb39024ed0974e0f60d9292156_Sections_0__Fields_0__Value">Last</label>
<span class="field-validation-valid help-block" data-valmsg-for="wffm26cf3ccb39024ed0974e0f60d9292156.Sections[0].Fields[0].Value" data-valmsg-replace="true">
</span>
</span>
</div>
Steps that i followed change html structure of WFFM.
WFFM using Sitecore.Forms.Mvc.Controllers.FormController and Its using default index action. By this it is using ~\Views\Forms\Index.cshtml on root web site.
Its basically using Editor for template.
So in my case i need to find out name section and need to change my html structure. From my findings SectionViewModel.cshtml is responsible for rendering all sections.
I have create one method to check whether current section needs to customized or not.
#if
(Renderer.IsCustomisedSection(Model))
Below my full SectionViewModel view file. (~\Views\Form\EditorTemplates\SectionViewModel.cshtml)
#using Sitecore.Forms.Mvc.Html
#using AAA.Foundation.HtmlHelper.WffmRenderer;
#model Sitecore.Forms.Mvc.ViewModels.SectionViewModel
<!--Render customised action-->
#if (Renderer.IsCustomisedSection(Model))
{
var customisedFieldHtml = Html.EditorFor(x => Model.Fields);
#Html.Raw(Renderer.RenderCustomisedFieldSection(customisedFieldHtml))
}
else
<!--Render customised action Ends-->
if (Model.ShowTitle && !string.IsNullOrEmpty(Model.Title))
{
<fieldset class="#Model.CssClass">
<legend>#Html.BootstrapText("Title")</legend>
#if (Model.ShowInformation && !string.IsNullOrEmpty(Model.Information))
{
<p>#Html.BootstrapText("Information")</p>
}
<div class="row">
<div class="col-md-12">
#Html.EditorFor(x => Model.Fields)
</div>
</div>
</fieldset>
}
else
{
#Html.EditorFor(x => Model.Fields)
}
This is how i can catch Name section by model title.Below my renderer class file
public static bool IsCustomisedSection(Sitecore.Forms.Mvc.ViewModels.SectionViewModel model) {
bool result = false;
// Check the model needs to customised
if (model.Title == "Name") { // For Ex:
result = true;
}
return result;
}
Then i will call respective customize html section like below.
var customisedFieldHtml = Html.EditorFor(x => Model.Fields);
#Html.Raw(Renderer.RenderCustomisedFieldSection(customisedFieldHtml))
Using "Html.EditorFor(x => Model.Fields)" this i can get default generated html. Then i will pass it to my customise render method. This will identify which sites and which section rendere needs to apply.
public static HtmlString RenderCustomisedFieldSection(HtmlString
customisedSectionHtml)
{
string caseValue = "SiteName-SectionName";
HtmlString result = new HtmlString(string.Empty);
switch (caseValue) {
case "SiteName-SectionName":
result = SiteName_Renderer.NameSection(customisedSectionHtml);
break;
}
return result;
}
My final customised html rendere method like below. I am using html agility pack to reframe the htmls.
public static HtmlString NameSection(HtmlString rawHtml)
{
HtmlNode customisedRoot = null;
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(rawHtml.ToString());
// Find each form group elements
var groupHtml = doc.DocumentNode
.Descendants("div")
.Where(d =>
d.Attributes.Contains("class")
&&
d.Attributes["class"].Value.Contains("form-group")
);
if (groupHtml.Count() > 0)
{
// Initialise root
customisedRoot = groupHtml.First().Clone();
customisedRoot.RemoveAllChildren();
// Customised the html
foreach (HtmlNode htmlNode in groupHtml)
{
HtmlDocument innerRootDoc = new HtmlDocument();
HtmlNode innerRoot = innerRootDoc.CreateElement("span");
var helpBlock = htmlNode.Descendants("span").Where(d =>
d.Attributes.Contains("class")
&&
d.Attributes["class"].Value.Contains("help-block")
);
innerRoot.PrependChild(helpBlock.FirstOrDefault());
var label = htmlNode.Descendants("label");
innerRoot.PrependChild(label.FirstOrDefault());
var inputs = htmlNode.Descendants("input");
foreach (HtmlNode inputsNode in inputs)
{
innerRoot.PrependChild(inputsNode);
}
customisedRoot.PrependChild(innerRoot);
}
}
return (customisedRoot!=null)?new HtmlString(customisedRoot.OuterHtml): new HtmlString(String.Empty);
}
By this approach i can able to customize WFFM web form html.
Below are i have tested after my html changes.
Does validation working or not in website.
If i submit the form will it available in form-reports section.In download excel whether submitted value will present or not.
So all the above cases or passed.
My query is above approach will break any other functionality.

Related

Livewire form submit with multiple wire:model input name

How can I let livewire know that a model is a particular modal
I have this in my livewire component
public $itemname;
public function updateReceivedKg()
{
$this->validate([
'itemname' => 'required',
]);
dump($this->itemname)
}
On livewire view, I have this
#foreach($result->products as $index=>$data)
<form wire:submit.prevent="updateReceivedKg()">
<div class="input-group">
<input required wire:model.defer="itemname" type="text" class="form-control">
<span class="input-group-append">
<button type="submit" class="btn btn-sm btn-success">Update</button>
</span>
</div>
</form>
#endforeach
After generating the form, I have about 11 forms. The issue is that livewire always submit the last itemname that was entered. For example, if on the first form, I entered "Mango" and go to another form and enter "Apple", if I go back to the form which I have already written "Mango" and click the submit (without typing anything) button, if I dump the submitted form and check the itemname, it shows it is the Apple. This is wrong because I submitted the Mango form.
In normal Laravel, I have no issue with this type of form submission. It will detect which form I submitted.
Please how can I achieve the same result using Livewire
You have the same itemname for a lot of elements. You should probably append the index to the modelname.
public $itemname1;
public $itemname2; // etc..
#foreach($result->products as $index=>$data)
<form wire:submit.prevent="updateReceivedKg()">
<div class="input-group">
<input required wire:model.defer="itemname{{$index}}" type="text" class="form-control">
<span class="input-group-append">
<button type="submit" class="btn btn-sm btn-success">Update</button>
</span>
</div>
</form>
#endforeach

In listing of data form is rendered when any input edited?

with livewire 1.3 / alpinejs 2.x.x I make listing of data with filter text
and selection inputs and clicking on “Search” button I need to run search when
“Search” button is clicked.
But search is run when text/selection input lose focus without clicking on “Search” button.
I see it by form's wire:loading block and 1 line in log file, which I trigger in render method
That is not what I need : I need to run render method only clicking on “Search” button.
I tried to use alpinejs, but failed...
In component app/Http/Livewire/Admin/AppNews.php I have:
<?php
namespace App\Http\Livewire\Admin;
use Carbon\Carbon;
use Livewire\Component;
use App\News;
use Livewire\WithPagination;
use Livewire\WithFileUploads;
class AppNews extends Component
{
use WithPagination;
use WithFileUploads;
public $filters = [
'title' => '',
'published' => '',
];
];
public $uploaded_file_name;
public $uploadedImageFilenameData;
public $uploadedNewsImage;
protected $listeners = ['fileUpload' => 'handleFileUpload'];
public $current_news_id;
public $updateMode = 'browse';
public function render()
{
\Log::info('-1 NewsRENDER $this->filters ::' . print_r($this->filters, true));
$news_rows_count = News
::getByTitle($this->filters['title'], true)
->getByPublished($this->filters['published'], true)
->count();
$backend_per_page = Settings::getValue('backend_per_page', CheckValueType::cvtInteger, 20);
$this->emit('app_news_opened', ['mode' => 'browse', 'id' => null]);
$newsPublishedValueArray = SetArrayHeader([['key' => '', 'label' => ' -Select published- ']], News::getNewsPublishedValueArray(true));
$newsDataRows = News
::getByTitle($this->filters['title'], true)
->getByPublished($this->filters['published'], true)
->with('creator')
->orderBy('news.created_at', 'desc')
->paginate($backend_per_page);
$newsDataIds = [];
foreach ($newsDataRows as $nextNews) {
$newsDataIds[] = $nextNews->id;
}
return view('livewire.admin.app-news.container', [
'newsDataRows' => $newsDataRows,
'newsDataIds' => $newsDataIds,
'form' => $this->form,
'news_rows_count' => $news_rows_count,
'newsPublishedValueArray' => $newsPublishedValueArray,
]);
}
and in the template resources/views/livewire/admin/app-news/container.blade.php :
<article class="admin_page_container">
<div class="card form-admin-news">
<div class="card-body card-block">
<div class="spinner-border" role="status" wire:loading>
<span class="sr-only">Loading...</span>
</div>
...
<fieldset class="bordered text-muted p-2 m-2" x-data="{ title: '{{$filters['title']}}', published: '{{$filters['published']}}' ,
publishedItems: <?php print str_replace('"',"'",json_encode( $newsPublishedValueArray) ) ?> } ">
<div> $filters::{{ var_dump($filters) }}</div>
title::<div x-html="title"></div>
published::<div x-html="published"></div>
<legend class="bordered">Filters</legend>
<dl class="block_2columns_md m-0 p-2">
<dt class="key_values_rows_label_13">
<label class="col-form-label" for="temp_filter_title">
By title
</label>
</dt>
<dd class="key_values_rows_value_13" >
<div class="content_with_right_button">
<div
class="content_with_right_button_left_content"
wire:model.lazy="filters.title"
>
<input
class="form-control admin_control_input"
type="text"
x-model="title"
x-on:blur="$dispatch('input', title)"
id="title"
>
</div>
<div class="content_with_right_button_right_button pl-2">
<button class="btn btn-outline-secondary nowrap_block" wire:click="makeSearch( )">
{!! $viewFuncs->showAppIcon('filter') !!}Search
</button>
</div>
</div>
</dd>
</dl>
<dl class="block_2columns_md m-0 p-2">
<dt class="key_values_rows_label_13">
<label class="col-form-label" for="temp_filter_published">
By published
</label>
</dt>
<dd
class="key_values_rows_value_13"
wire:model.lazy="filters.published"
>
<select
x-model="published"
x-on:blur="$dispatch('select', published)"
id="published"
class="form-control editable_field admin_control_input"
>
<template x-for="nextPublishedItem in publishedItems">
<option :value="nextPublishedItem.key" x-text="nextPublishedItem.label"></option>
</template>
</select>
#error('form.published')
<div class="validation_error">{{ clearValidationError($message,['form.'=>'']) }}</div> #enderror
</dd>
</dl>
</fieldset> <!-- Filters -->
...
#endif {{-- #if($updateMode=='browse')--}}
#endif {{-- #if($updateMode=='browse')--}}
#if(count($newsDataRows) > 0)
<div class="table-responsive table-wrapper-for-data-listing" x-data="selectedNewsIdsBoxXData()">
<table>
...
</table>
</div> <!-- <div class="table-responsive table-wrapper-for-data-listing"> -->
#endif {{-- #if(count($newsDataRows) > 0) --}}
#endif {{-- #if($updateMode=='browse') --}}
</div> <!-- <div class="card-body card-block"> -->
</div> <!-- <div class="card"> -->
</article> <!-- page_content_container -->
Which is the valid way?
Modified BLOCK 2:
I try another way with using of alpinejs2 : I try to use it in this case, as when public var of component is changed:
with dispatch methid when button “Search” is clicked
<div class="card form-admin-facilities" x-data="adminFacilitiesComponent()">
...
filter_name: {{$filter_name}}<br>
...
temp_filter_name: <span x-html="temp_filter_name"></span><br>
...
<fieldset class="bordered text-muted p-2 m-2">
<legend class="bordered">Filters</legend>
<div class="content_with_right_button" wire:model.lazy="filter_name">
<div class="content_with_right_button_left_content" >
<input
class="form-control admin_filter_input"
x-model="temp_filter_name"
type="text"
>
</div>
<div class="content_with_right_button_right_button pl-2" >
<button class="btn btn-outline-secondary" #click="$dispatch('input', temp_filter_name)" type="button">Search
</button>
<!-- In more complicated form can be several filter fields : text and select inputs -->
</div>
</div>
</fieldset> <!-- Filters -->
...
<script>
function adminFacilitiesComponent() {
return {
temp_filter_name:'',
and in the component I defined public $filter_name var, which is used in render method :
class Facilities extends Component
{
public $form= [
'name'=>'',
'descr'=> '',
'created_at'=> '',
'is_reopen' => false,
];
public $current_facility_id;
public $filter_name= '';
public $updateMode = 'browse';
public function render()
{
\Log::info( '-1 render Facilities $this->filter_name ::' . print_r( $this->filter_name, true ) );
$this->facility_rows_count = Facility
::getByName($this->filter_name, true)
->count();
$backend_per_page = Settings::getValue('backend_per_page', CheckValueType::cvtInteger, 20);
return view('livewire.admin.facilities.container', [
'facilityDataRows' => Facility
::orderBy('created_at', 'desc')
->getByName($this->filter_name, true)
->paginate($backend_per_page),
'facility_rows_count'=> $this->facility_rows_count
]);
}
But it does not work as I expect : entering value in text input when this input lose focus
form is rendered again. I expected form to be rendered only when I click on “Search” button
and form will be rendered with new entered value. I do not use blur event for text input and
do not understand why the form is rendered when this input lose focus?
Modified BLOCK 3:
Using x-ref= I do :
<div class="content_with_right_button" wire:model.lazy="filter_name">
<div class="content_with_right_button_left_content" >
<input
class="form-control admin_filter_input"
x-model="temp_filter_name"
x-ref="searched"
type="text"
> 1111111
</div>
<div class="content_with_right_button_right_button pl-2" >
<button class="btn btn-outline-secondary nowrap_block" wire:click="makeSearch(this.$refs.searched)" type="button">
Search
</button>
</div>
</div>
But I got error clicking on search button:
VM1983:6 Uncaught TypeError: Cannot read property 'searched' of undefined
at eval (eval at parseOutMethodAndParams (directive.js:55), <anonymous>:6:27)
at _default.parseOutMethodAndParams (directive.js:55)
Looks like it is impossible to use this.$refs. value in
wire:click="makeSearch .
I need to trigger component method
public function makeSearch($search_value='')
{
and send entered value into it.
Looks like the way I tried was invalid.
If there is a valid way?
Thanks!
In your modified block 2, you should use wire:ignore in base div of your AlpineJS component. This will make livewire ignore the component.
<div class="card form-admin-facilities" wire:ignore x-data="adminFacilitiesComponent()">
Your $dispatch() should handle setting the value when you click the button.
In order to make livewire ignore the component just add wire:ignore to your component's div in modified block 2 and then in your dispatch method you can write the logic that happens after clicking the button.

How to validate email id in angularJs using ng-pattern

Am trying to validate an Email id field in angularJs using ng-pattern directive.
But am new to AngularJs. I need to show an error message as soon as the user enters the wrong email id.
The code which I have below is am trying to solve. Help me out with using ng-pattern for getting the proper result.
<script type="text/javascript" src="/Login/script/ang.js"></script>
<script type="text/javascript">
function Ctrl($scope) {
$scope.text = 'enter email';
$scope.word = /^[a-z]+[a-z0-9._]+#[a-z]+\.[a-z.]{2,5}$/;
}
</script>
</head>
<body>
<form name="myform" ng-controller="Ctrl">
<input type="text" ng-pattern="word" name="email">
<span class="error" ng-show="myform.email.$error.pattern">
invalid email!
</span>
<input type="submit" value="submit">
</form>
</body>
If you want to validate email then use input with type="email" instead of type="text". AngularJS has email validation out of the box, so no need to use ng-pattern for this.
Here is the example from original documentation:
<script>
function Ctrl($scope) {
$scope.text = 'me#example.com';
}
</script>
<form name="myForm" ng-controller="Ctrl">
Email: <input type="email" name="input" ng-model="text" required>
<br/>
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.email">
Not valid email!</span>
<br>
<tt>text = {{text}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
<tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>
</form>
For more details read this doc: https://docs.angularjs.org/api/ng/input/input%5Bemail%5D
Live example: http://plnkr.co/edit/T2X02OhKSLBHskdS2uIM?p=info
UPD:
If you are not satisfied with built-in email validator and you want to use your custom RegExp pattern validation then ng-pattern directive can be applied and according to the documentation the error message can be displayed like this:
The validator sets the pattern error key if the ngModel.$viewValue
does not match a RegExp
<script>
function Ctrl($scope) {
$scope.text = 'me#example.com';
$scope.emailFormat = /^[a-z]+[a-z0-9._]+#[a-z]+\.[a-z.]{2,5}$/;
}
</script>
<form name="myForm" ng-controller="Ctrl">
Email: <input type="email" name="input" ng-model="text" ng-pattern="emailFormat" required>
<br/><br/>
<span class="error" ng-show="myForm.input.$error.required">
Required!
</span><br/>
<span class="error" ng-show="myForm.input.$error.pattern">
Not valid email!
</span>
<br><br>
<tt>text = {{text}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
<tt>myForm.$error.pattern = {{!!myForm.$error.pattern}}</tt><br/>
</form>
Plunker: https://plnkr.co/edit/e4imaxX6rTF6jfWbp7mQ?p=preview
There is nice example how to deal with this kind of problem modyfing built-in validators angulardocs. I have only added more strict validation pattern.
app.directive('validateEmail', function() {
var EMAIL_REGEXP = /^[_a-z0-9]+(\.[_a-z0-9]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;
return {
require: 'ngModel',
restrict: '',
link: function(scope, elm, attrs, ctrl) {
// only apply the validator if ngModel is present and Angular has added the email validator
if (ctrl && ctrl.$validators.email) {
// this will overwrite the default Angular email validator
ctrl.$validators.email = function(modelValue) {
return ctrl.$isEmpty(modelValue) || EMAIL_REGEXP.test(modelValue);
};
}
}
};
});
And simply add
<input type='email' validate-email name='email' id='email' ng-model='email' required>
According to the answer of #scx ,I created a validation for GUI
app.directive('validateEmail', function() {
var EMAIL_REGEXP = /^[_a-z0-9]+(\.[_a-z0-9]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;
return {
link: function(scope, elm) {
elm.on("keyup",function(){
var isMatchRegex = EMAIL_REGEXP.test(elm.val());
if( isMatchRegex&& elm.hasClass('warning') || elm.val() == ''){
elm.removeClass('warning');
}else if(isMatchRegex == false && !elm.hasClass('warning')){
elm.addClass('warning');
}
});
}
}
});
And simply add :
css
.warning{
border:1px solid red;
}
html
<input type='email' validate-email name='email' id='email' ng-model='email' required>
This is jQuery Email Validation using Regex Expression. you can also use the same concept for AngularJS if you have idea of AngularJS.
var expression = /^[\w\-\.\+]+\#[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
Source.
You can use ng-messages
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular-messages.min.js"></script>
include the module
angular.module("blank",['ngMessages']
in html
<input type="email" name="email" class="form-control" placeholder="email" ng-model="email" required>
<div ng-messages="myForm.email.$error">
<div ng-message="required">This field is required</div>
<div ng-message="email">Your email address is invalid</div>
</div>
Below is the fully qualified pattern for email validation.
<input type="text" pattern="/^[_a-z0-9]+(\.[_a-z0-9]+)*#[a-z0-9-]*\.([a-z]{2,4})$/" ng-model="emailid" name="emailid"/>
<div ng-message="pattern">Please enter valid email address</div>
Now, Angular 4 has email validator built-in
https://github.com/angular/angular/blob/master/CHANGELOG.md#features-6
https://github.com/angular/angular/pull/13709
Just add email to the tag. For example
<form #f="ngForm">
<input type="email" ngModel name="email" required email>
<button [disabled]="!f.valid">Submit</button>
<p>Form State: {{f.valid?'VALID':'INVALID'}}</p>
</form>
angularjs controller way, just an example to look for one or more email in the body of a message.
sp = $scope.messagebody; // email message body
if (sp != null && sp.match(/([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)\S+/)) {
console.log('Error. You are not allowed to have an email in the message body');
}
I tried #Joanna's method and tested on the following websites and it didn't work.
https://regex101.com/
https://www.regextester.com/
https://regexr.com/
I then modified it to and it worked.
/([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)\S+
I have tried wit the below regex it is working fine.
Email validation : \w+([-+.']\w+)#\w+([-.]\w+).\w+([-.]\w+)*
Spend some time to make it working for me.
Requirement:
single or comma separated list of e-mails with domains ending name.surname#gmail.com or team-email#list.gmail.com
Controller:
$scope.email = {
EMAIL_FORMAT: /^\w+([\.-]?\w+)*#(list.)?gmail.com+((\s*)+,(\s*)+\w+([\.-]?\w+)*#(list.)?gmail.com)*$/,
EMAIL_FORMAT_HELP: "format as 'your.name#gmail.com' or comma separated 'your.name#gmail.com, my.name#list.gmail.com'"
};
HTML:
<ng-form name="emailModal">
<div class="form-group row mb-3">
<label for="to" class="col-sm-2 text-right col-form-label">
<span class="form-required">*</span>
To
</label>
<div class="col-sm-9">
<input class="form-control" id="to"
name="To"
ng-required="true"
ng-pattern="email.EMAIL_FORMAT"
placeholder="{{email.EMAIL_FORMAT_HELP}}"
ng-model="mail.to"/>
<small class="text-muted" ng-show="emailModal.To.$error.pattern">wrong</small>
</div>
</div>
</ng-form>
I found good online regex testing tool.
Covered my regex with tests:
https://regex101.com/r/Dg2iAZ/6/tests
Use below regular expression
^[_\.0-9a-z-]+#([0-9a-z][0-9a-z-]+)+((\.)[a-z]{2,})+$
It allows
test#test.com
test#test.co.in
test#test.gov.us
test#test.net
test#test.software

Ajax, Django, Jquery Model Form

Built a successful working ModelForm and its fully functional.
My next step was to add Ajax to it and it also worked out pretty well. The Jquery that I used was 1.3.2 version which is pretty old but it worked.
The problem came up when I tried to add bootstrap 2 DATE fields.
Using CHECKIN & CHECKOUT values that I have added to my form and it worked.
It required higher version of jquery so I used the recent one 1.9.1.
But when I used it my form is working except 1 little issues when I submit the form
and there not filled out required fields it will show me those fields but SUBMIT button is
disabled. When I use jquery 1.3.2 all is working 100% except the 2 fields for Bootstrap
DATEPICKER that requires higher jquery version.
Input Fields in the Form: Departure & Return are Date Picker Fields
I didnt include the Bootstrap Scripts they are same from the Bootsrap site.
When I use:
<script src="/media/js/jquery/1.9.1.jquery.min.js" type="text/javascript"></script>
Departure & Return are Date Picker Fields are Working but after submitting it with empty
other fields - it will show you which fields are required but Submit button is disabled.
If I use:
<script src="/media/js/jquery/1.3.2.jquery.min.js" type="text/javascript"></script>
Form is working with ajax 100% but I cant use Departure & Return are Date Picker Fields
(which give me choice to select date - I have to manually type it).
For reference I used this tutorial.
Look at the Category ModelForm Ajax
My question is I can I achieve this form to be working on 1.9.1 Jquery Version with also Date
picker Fields that I can choosed from the calendar.
At the bottom I am including screenshots.
Here is the code:
MODELS.PY
TRIP_TYPES = (
('one way', 'One Way'),
('round trip', 'Round Trip'),
('multi-leg', 'Multi-Leg'),
)
class Request_Quote(models.Model):
trip_type = models.CharField(max_length=10, choices=TRIP_TYPES, default='one way')
company_name = models.CharField(max_length=200)
individual_name = models.CharField(max_length=200)
phone = models.CharField(max_length=200)
email = models.CharField(max_length=200)
from_country = models.CharField(max_length=200)
to_country = models.CharField(max_length=200)
from_city = models.CharField(max_length=200)
to_city = models.CharField(max_length=200)
departure_date = models.CharField(max_length=200)
return_date = models.CharField(max_length=200)
number_of_passengers = models.CharField(max_length=200)
VIEWS.PY
def quote(request):
if request.method == "POST":
form = Request_QuoteForm(request.POST)
## Handle AJAX ##
if request.is_ajax():
if form.is_valid():
form.save()
# Get a list of Categories to return
quotes = Request_Quote.objects.all().order_by('individual_name')
# Create a dictionary for our response data
data = {
'error': False,
'message': 'Request Quote Added Successfully',
# Pass a list of the 'name' attribute from each Category.
# Django model instances are not serializable
'quotes': [q.individual_name for q in quotes],
}
else:
# Form was not valid, get the errors from the form and
# create a dictionary for our error response.
data = {
'error': True,
'message': "Please try again!",
'trip_type_error': str(form.errors.get('trip_type', '')),
'company_name_error': str(form.errors.get('company_name', '')),
'individual_name_error': str(form.errors.get('individual_name', '')),
'phone_error': str(form.errors.get('phone', '')),
'email_error': str(form.errors.get('email', '')),
'from_country_error': str(form.errors.get('from_country', '')),
'to_country_error': str(form.errors.get('to_country', '')),
'from_city_error': str(form.errors.get('from_city', '')),
'to_city_error': str(form.errors.get('to_city', '')),
'departure_date_error': str(form.errors.get('departure_date', '')),
'return_date_error': str(form.errors.get('return_date', '')),
'number_of_passengers_error': str(form.errors.get('number_of_passengers', '')),
}
# encode the data as a json object and return it
return http.HttpResponse(json.dumps(data))
if form.is_valid():
form.save()
return http.HttpResponseRedirect('/request-quote/')
else:
form = Request_QuoteForm()
quotes = Request_Quote.objects.all().order_by('individual_name')
return render_to_response('quote.html', {'title': 'Request Quote', 'form': form, 'quotes': quotes}, context_instance=RequestContext(request))
TEMPLATES:
<script type="text/javascript">
// prepare the form when the DOM is ready
$(document).ready(function() {
$("#add_cat").ajaxStart(function() {
// Remove any errors/messages and fade the form.
$(".form_row").removeClass('errors');
$(".form_row_errors").html('');
$("#add_cat").fadeTo('slow', 0.33);
$("#add_cat_btn").attr('disabled', 'disabled');
$("#message").addClass('hide');
});
// Submit the form with ajax.
$("#add_cat").submit(function(){
$.post(
// Grab the action url from the form.
"#add_cat.getAttribute('action')",
// Serialize the form data to send.
$("#add_cat").serialize(),
// Callback function to handle the response from view.
function(resp, testStatus) {
if (resp.error) {
// check for field errors
if (resp.trip_type_error != '') {
$("#trip_type_row").addClass('errors');
$("#trip_type_errors").html(resp.trip_type_error);
}
if (resp.company_name_error != '') {
$("#company_name_row").addClass('errors');
$("#company_name_errors").html(resp.company_name_error);
}
if (resp.individual_name_error != '') {
$("#individual_name_row").addClass('errors');
$("#individual_name_errors").html(resp.individual_name_error);
}
if (resp.phone_error != '') {
$("#phone_row").addClass('errors');
$("#phone_errors").html(resp.phone_error);
}
if (resp.email_error != '') {
$("#email_row").addClass('errors');
$("#email_errors").html(resp.email_error);
}
if (resp.from_country_error != '') {
$("#from_country_row").addClass('errors');
$("#from_country_errors").html(resp.from_country_error);
}
if (resp.to_country_error != '') {
$("#to_country_row").addClass('errors');
$("#to_country_errors").html(resp.to_country_error);
}
if (resp.from_city_error != '') {
$("#from_city_row").addClass('errors');
$("#from_city_errors").html(resp.from_city_error);
}
if (resp.to_city_error != '') {
$("#to_city_row").addClass('errors');
$("#to_city_errors").html(resp.to_city_error);
}
if (resp.departure_date_error != '') {
$("#departure_date_row").addClass('errors');
$("#departure_date_errors").html(resp.departure_date_error);
}
if (resp.return_date_error != '') {
$("#return_date_row").addClass('errors');
$("#return_date_errors").html(resp.return_date_error);
}
if (resp.number_of_passengers_error != '') {
$("#number_of_passengers_row").addClass('errors');
$("#number_of_passengers_errors").html(resp.number_of_passengers_error);
}
$("#add_cat").fadeTo('slow', 1);
$("#add_cat_btn").attr('disabled', false);
} else {
// No errors. Rewrite the category list.
$("#categories").fadeTo('fast', 0);
var text = new String();
for(i=0; i<resp.quotes.length ;i++){
var m = resp.quotes[i]
text += "<li>" + m + "</li>"
}
$("#categories").html(text);
$("#categories").fadeTo('slow', 1);
$("#id_trip_type").attr('value', '');
$("#id_company_name").attr('value', '');
$("#id_individual_name").attr('value', '');
$("#id_phone").attr('value', '');
$("#id_email").attr('value', '');
$("#id_from_country").attr('value', '');
$("#id_to_country").attr('value', '');
$("#id_from_city").attr('value', '');
$("#id_to_city").attr('value', '');
$("#id_departure_date").attr('value', '');
$("#id_return_date").attr('value', '');
$("#id_number_of_passengers").attr('value', '');
}
// Always show the message and re-enable the form.
$("#message").html(resp.message);
$("#message").removeClass('hide');
$("#add_cat").fadeTo('slow', 1);
$("#add_cat_btn").attr('disabled', '');
// Set the Return data type to "json".
}, "json");
return false;
});
});
</script>
<div id="content" class="span9" style="">
<h1>Request Quote</h1>
<div id='message'></div>
<form id='add_cat' method='post' action='.'><input type='hidden' name='csrfmiddlewaretoken' value='KblPqgczzMK7skak162xe4aOL6bLot2A' />
<div class='form_row' id='trip_type_row'>
<div class="span2">
<label for="id_trip_type">Trip type</label>
</div>
<div class="span4">
<select id="id_trip_type" name="trip_type">
<option value="one way" selected="selected">One Way</option>
<option value="round trip">Round Trip</option>
<option value="multi-leg">Multi-Leg</option>
</select>
</div>
<div class="span6">
<p id='trip_type_errors' class="form_row_errors"></p>
</div>
</div>
<div class='form_row' id='company_name_row'>
<div class="span2">
<label for="id_company_name">Company name</label>
</div>
<div class="span4">
<input id="id_company_name" maxlength="200" name="company_name" type="text" />
</div>
<div class="span6">
<p id='company_name_errors' class="form_row_errors" style="color: red;"></p>
</div>
</div>
<div class='form_row' id='individual_name_row'>
<div class="span2">
<label for="id_individual_name">Individual name</label>
</div>
<div class="span4">
<input id="id_individual_name" maxlength="200" name="individual_name" type="text" />
</div>
<div class="span6">
<p id='individual_name_errors' class="form_row_errors"></p>
</div>
</div>
<div class='form_row' id='phone_row'>
<div class="span2">
<label for="id_phone">Phone</label>
</div>
<div class="span4">
<input id="id_phone" maxlength="200" name="phone" type="text" />
</div>
<div class="span6">
<p id='phone_errors' class="form_row_errors"></p>
</div>
</div>
<div class='form_row' id='email_row'>
<div class="span2">
<label for="id_email">Email</label>
</div>
<div class="span4">
<input id="id_email" maxlength="200" name="email" type="text" />
</div>
<div class="span6">
<p id='email_errors' class="form_row_errors"></p>
</div>
</div>
<div class='form_row' id='from_country_row'>
<div class="span2">
<label for="id_from_country">From country</label>
</div>
<div class="span4">
<input id="id_from_country" maxlength="200" name="from_country" type="text" />
</div>
<div class="span6">
<p id='from_country_errors' class="form_row_errors"></p>
</div>
</div>
<div class='form_row' id='to_country_row'>
<div class="span2">
<label for="id_to_country">To country</label>
</div>
<div class="span4">
<input id="id_to_country" maxlength="200" name="to_country" type="text" />
</div>
<div class="span6">
<p id='to_country_errors' class="form_row_errors"></p>
</div>
</div>
<div class='form_row' id='from_city_row'>
<div class="span2">
<label for="id_from_city">From city</label>
</div>
<div class="span4">
<input id="id_from_city" maxlength="200" name="from_city" type="text" />
</div>
<div class="span6">
<p id='from_city_errors' class="form_row_errors"></p>
</div>
</div>
<div class='form_row' id='to_city_row'>
<div class="span2">
<label for="id_to_city">To city</label>
</div>
<div class="span4">
<input id="id_to_city" maxlength="200" name="to_city" type="text" />
</div>
<div class="span6">
<p id='to_city_errors' class="form_row_errors"></p>
</div>
</div>
<div class='form_row' id='departure_date_row'>
<div class="span2">
<label for="id_departure_date">Departure date</label>
</div>
<div class="span4">
<input id="id_departure_date" maxlength="200" name="departure_date" type="text" />
</div>
<div class="span6">
<p id='departure_date_errors' class="form_row_errors"></p>
</div>
</div>
<div class='form_row' id='return_date_row'>
<div class="span2">
<label for="id_return_date">Return date</label>
</div>
<div class="span4">
<input id="id_return_date" maxlength="200" name="return_date" type="text" />
</div>
<div class="span6">
<p id='return_date_errors' class="form_row_errors"></p>
</div>
</div>
<div class='form_row' id='number_of_passengers_row'>
<div class="span2">
<label for="id_number_of_passengers">Number of passengers</label>
</div>
<div class="span4">
<input id="id_number_of_passengers" maxlength="200" name="number_of_passengers" type="text" />
</div>
<div class="span6">
<p id='number_of_passengers_errors' class="form_row_errors"></p>
</div>
</div>
<input id="add_cat_btn" type='submit' value="save">
</form>
</div><!-- End content -->
Screenshots:
These are images with not functional after Submission Form Submit button but Date Picker
Fields are working becasue Jquery 1.9.1 was used:
Screen 1:
Screen 2:
This is an image with not functional Date Picker because Jquery 1.3.2 was used and Submit
Button is enabled after submision:
Thanks for help.
I managed to solve the problem, the problem was with the newest jquery using different variables. Updated the code above with the answer.
Here is the code:
TEMPLATES:
<script type="text/javascript">
// prepare the form when the DOM is ready
$(document).ready(function() {
$("#add_cat").ajaxStart(function() {
// Remove any errors/messages and fade the form.
$(".form_row").removeClass("errors");
$(".form_row_errors").html('');
$("#add_cat").fadeTo('slow', 0.33);
$("#add_cat_btn").attr("disabled", "disabled");
$("#message").addClass('hide');
});
// Submit the form with ajax.
$("#add_cat").submit(function(){
$.post(
// Grab the action url from the form.
"#add_cat.getAttribute('action')",
// Serialize the form data to send.
$("#add_cat").serialize(),
// Callback function to handle the response from view.
function(resp, testStatus) {
$(".form_row").removeClass("errors");
$("#trip_type_errors").html("");
$("#company_name_errors").html("");
$("#individual_name_errors").html("");
$("#phone_errors").html("");
$("#email_errors").html("");
$("#from_country_errors").html("");
$("#to_country_errors").html("");
$("#from_city_errors").html("");
$("#to_city_errors").html("");
$("#departure_date_errors").html("");
$("#return_date_errors").html("");
$("#number_of_passengers_errors").html("");
if (resp.error) {
// check for field errors
if (resp.trip_type_error != '') {
$("#trip_type_row").addClass('errors');
$("#trip_type_errors").html(resp.trip_type_error);
}
if (resp.company_name_error != '') {
$("#company_name_row").addClass('errors');
$("#company_name_errors").html(resp.company_name_error);
}
if (resp.individual_name_error != '') {
$("#individual_name_row").addClass('errors');
$("#individual_name_errors").html(resp.individual_name_error);
}
if (resp.phone_error != '') {
$("#phone_row").addClass('errors');
$("#phone_errors").html(resp.phone_error);
}
if (resp.email_error != '') {
$("#email_row").addClass('errors');
$("#email_errors").html(resp.email_error);
}
if (resp.from_country_error != '') {
$("#from_country_row").addClass('errors');
$("#from_country_errors").html(resp.from_country_error);
}
if (resp.to_country_error != '') {
$("#to_country_row").addClass('errors');
$("#to_country_errors").html(resp.to_country_error);
}
if (resp.from_city_error != '') {
$("#from_city_row").addClass('errors');
$("#from_city_errors").html(resp.from_city_error);
}
if (resp.to_city_error != '') {
$("#to_city_row").addClass('errors');
$("#to_city_errors").html(resp.to_city_error);
}
if (resp.departure_date_error != '') {
$("#departure_date_row").addClass('errors');
$("#departure_date_errors").html(resp.departure_date_error);
}
if (resp.return_date_error != '') {
$("#return_date_row").addClass('errors');
$("#return_date_errors").html(resp.return_date_error);
}
if (resp.number_of_passengers_error != '') {
$("#number_of_passengers_row").addClass('errors');
$("#number_of_passengers_errors").html(resp.number_of_passengers_error);
}
} else {
// No errors. Rewrite the category list.
$("#categories").fadeTo('fast', 0);
var text = new String();
for(i=0; i<resp.quotes.length ;i++){
var m = resp.quotes[i]
text += "<li>" + m + "</li>"
}
$("#categories").html(text);
$("#categories").fadeTo('slow', 1);
$("#id_trip_type").val("");
$("#id_company_name").val("");
$("#id_individual_name").val("");
$("#id_phone").val("");
$("#id_email").val("");
$("#id_from_country").val("");
$("#id_to_country").val("");
$("#id_from_city").val("");
$("#id_to_city").val("");
$("#id_departure_date").val("");
$("#id_return_date").val("");
$("#id_number_of_passengers").val("");
}
// Always show the message and re-enable the form.
$("#message").html(resp.message);
$("#message").removeClass('hide');
$("#add_cat").fadeTo('slow', 1);
$("#add_cat_btn").removeAttr("disabled");//attr('disabled', '');
// Set the Return data type to "json".
}, "json");
return false;
});
});
</script>

Form Validations in EmberJS

I'm just wondering what the general pattern for validating forms in EmberJS? For my App.IndexView I have a form and when you click the submit button the target set to the view so I can do some validation. This works great up to the point where I need to do something with the fields that have errors. I would like to just add a class to the fields with errors but not really sure how to do it. Should the IndexView validate the form or should I create a view for each field that validates its self on blur? Below is what I have in my IndexView.
App.IndexView = Ember.View.extend
create: (model) ->
valid = #_validate model
if valid is true
#get('controller').send 'createUser'
else
# HANDLE THE FIELDS WITH ERRORS
_validate: (model) ->
invalid = []
validations = {
firstName: #_validateString model.get 'firstName'
lastName: #_validateString model.get 'lastName'
email: #_validateEmail model.get 'email'
password: #_validatePassword model.get 'password'
accountType: #_validateString model.get 'accountType'
}
# This will get all of the values then runs uniq to see if the
# form is valid
validForm = _.chain(validations).values().uniq().value()
if validForm.length is 1 and validForm[0]
true
else
# other wise build up an array of the fields with issues
for field, val of validations
if val is false
invalid.push field
invalid
_validateString: (str) ->
return false unless str
if str isnt '' then true else false
_validateEmail: (str) ->
pattern = /^(([^<>()[\]\\.,;:\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,}))$/
pattern.test str
_validatePassword: (str) ->
return false unless str
if str.length >= 6 then true else false
and the template
<div class="row">
<div class="span12">
<div class="signup">
<form class="form-horizontal offset3">
<div class="control-group">
<label class="control-label" for="first_name">First Name</label>
<div class="controls">
{{ view Ember.TextField placeholder="First Name" required="true" valueBinding='firstName' name='first_name' viewName='firstNameField'}}
</div>
</div>
<div class="control-group">
<label class="control-label" for="last_name">Last Name</label>
<div class="controls">
{{ view Ember.TextField placeholder="Last Name" required="true" valueBinding='lastName' name='last_name' viewName='lastNameField'}}
</div>
</div>
<div class="control-group">
<label class="control-label" for="email">Email</label>
<div class="controls">
{{ view Ember.TextField placeholder="Email" required="true" type="email" valueBinding='email' name='email' viewName='emailField'}}
</div>
</div>
<div class="control-group">
<label class="control-label" for="password">Password</label>
<div class="controls">
{{ view Ember.TextField placeholder="Password" required="true" type="password" valueBinding='password' name='password' viewName='passwordField'}}
</div>
</div>
<div class="control-group">
<label class="control-label" for="">Account Type</label>
<div class="controls">
{{#view Ember.RadioButtonGroup name="accountType" required="true" valueBinding="accountType"}}
<label class="radio">
{{view RadioButton checked='false' value="landlord"}}
Landlord
</label>
<label class="radio">
{{view RadioButton checked='false' required="true" value="tenant"}}
Tenant
</label>
{{/view}}
</div>
</div>
<div class="control-group">
<div class="controls">
<input class="btn btn-primary" {{action create model target='view' }} type="submit" value="Sign Up">
</div>
</div>
</form>
</div>
</div>
</div>
I'm just wondering what the general pattern for validating forms in EmberJS?
There seem to be several patterns in use. It depends quite a bit on what is being validated, with the general strategy being to keep business logic far from the view layer as possible. Here are some links that may prove useful:
validations-in-emberjs-application.html recommends performing validation at the controller level, with views are used to trigger validation when focus changes. This screencast demonstrates how this pattern can be used to validate a few simple form-fields.
Asynchronous-Form-Field-Validation-With-Ember provides a few reusable components that can be used to perform simple validations at the view layer.
ember-validations is a library that can be used to add active-record style validation capabilities to any ember-object
For my App.IndexView I have a form and when you click the submit button the target set to the view so I can do some validation. This works great up to the point where I need to do something with the fields that have errors. I would like to just add a class to the field of erro but not really sure how to do it.
since you're looking to validate a number of fields at once it might make more sense to move this validation logic into the controller. Either way, typically you would bind class attributes for a given field to a property as follows:
<div class="controls" {{bindAttr class=firstNameError:error:success}}>
{{ view Ember.TextField placeholder="First Name" required="true" valueBinding='firstName' name='first_name' viewName='firstNameField'}}
</div>
So with this in place add a firstNameError property that returns true/false depending on results of your validation. Given your implementation it would probably make sense to set this property when _validate is run, but it could also be a computed property that performs validation in real-time.
Should the IndexView validate the form or should I create a view for each field that validates its self on blur?
That really depends on what you want the user experience to be like. FWIW my vote is to go with on-blur.