how to add pattern validation in angular - c#

I am having a model with a float propert
public float Amount { get; set; }
and a text box to display anf edit the value of amount.
only number accepted
my text box should allow characters and on while entering it should show error message
here i want to add a validation to restrict only number and decimal point.
here my validation is not working when i enter characters in the text box.
When i checked i can see that upon entering characters on text box {{model.amount}} is turned to blank . I think this is the problem. Can someone suggest what to do in this scenario

You Can add ng-patter or add html5 input type number with step attr.
HTML5
<input type="number" name="myDecimal" placeholder="Decimal" ng-model="myDecimal" *step="0.01"* />
ng-pattern
<form name="myForm">
<input type="text" name="test1" data-ng-pattern="/^[0-9]+(\.[0-9]{1,2})?$/" data-ng-model="model.amount" />
<span data-ng-show="myForm.test1.$error.pattern">invalid</span>
<span>{{model.amount}}</span><br/>
</form>
Ng-pattern with min and max
<form name="myForm">
<input type="text" name="test1" data-ng-pattern="/^(100(?:\.00)?|0(?:\.\d\d)?|\d?\d(?:\.\d\d)?)$/" data-ng-model="model.amount" />
<span data-ng-show="myForm.test1.$error.pattern">invalid</span>
<span>{{model.amount}}</span><br/>
</form>
Please check working Ex. here
https://plnkr.co/edit/WSqMHsLSCkRk7VVsNfHQ?p=preview

You can use ng-pattern to do this. It will compare the ng-model value with the pattern each time the value changes.
See the docs here

Try referring this:
var app = angular.module('myApp', []);
app.controller('validateCtrl', function($scope) {
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<h2>Validation Example</h2>
<form ng-app="myApp" ng-controller="validateCtrl"
name="myForm" novalidate>
<p>Enter Decimal:<br>
<input type="number" name="decimal" ng-model="decimal" required ng-pattern="/^[0-9]+(\.[0-9]{1,2})?$/">
<span style="color:red" ng-show="myForm.decimal.$dirty && myForm.decimal.$invalid">
<span ng-show="myForm.decimal.$error.required">please enter decimal value.</span>
<span ng-show="myForm.decimal.$invalid">only two decimal places are allwed.</span>
</p>
<p>
<input type="submit"
ng-disabled="myForm.decimal.$dirty && myForm.decimal.$invalid">
</p>
</form>

Related

Text not showing in textarea

I have a model with a fildValue1 parameter which has a string data type. when requested, the text can be displayed in the input tag but not in the textarea
<div>
<input type="text" asp-for="fildName1" value="#Model.fildName1" placeholder="name">
<textarea type="text" style="width: 200px" asp-for="fildValue1" placeholder="value">#Model.fildValue1</textarea>
<input type="checkbox" asp-for="fildInline1" > Inline
</div>
I tried different tags only works with Input tag. but i need line input capability
I have an encapsulated constructor like { get; set;} in a variable. I figured it out and it doesn't output value. When I change it to ="" it outputs the value, but now when I want to get it through form input it outputs an empty value
Change the
<textarea type="text" style="width: 200px" asp-for="fildValue1" placeholder="value">#Model.fildValue1</textarea>
TO
<textarea type="text" style="width: 200px" asp-for="fildValue1" placeholder="value"></textarea>

How to format exact with two digits after the decimal point in HTML

I'm trying to format the results with fixed 2 digits after the decimal point. (:F2 in C#). I expect the results when I press the arrow to be 1.0, 2.0, 3.0, ... 7.0, no 1, 2, 3, ..., 7. I would be very grateful if you could explain to me how this can be done.
<h1>Create Game</h1>
<section>
<div>
<form asp-action="Create" method="POST">
<label for="name">Name</label>
<input type="text" id="name" name="name" />
<label for="dlc">DLC</label>
<input type="text" id="dlc" name="dlc" />
<label for="price">Price</label>
<input type="number" min="0" step="any" id="price" name="price" />
<label for="platform">Platform</label>
<select name="platform">
<option id="platform" value="PC">PC</option>
<option id="platform" value="Mac">Mac</option>
<option id="platform" value="PlayStation 4">PlayStation 4</option>
<option id="platform" value="PlayStation 3">PlayStation 3</option>
</select>
<button class="button" type="submit">Create</button>
<button class="button cancel" type="button" onclick="location.href='/'">Cancel</button>
</form>
</div>
You can use the step HTML attribute.
<input type="number" step="0.01" value="1.0">
Please note that this will only work with a decimal step value (it won't work for 1 or 1.0).
If your step is an integer value, you can manipulate the input value with JavaScript:
document.querySelector("#my-input").onchange = function(e) {
this.value = parseFloat(this.value).toFixed(2);
};
<input id="my-input" type="number" step="1.0" value="1.0">
You can use autoNumeric plugin to fixed 2 digits after the decimal point. After autoNumeric plugin is downloaded and added in html file, following code can be used (input type should be text type)
<input type="text" id="price" name="price" />
<script type="text/javascript" src="js/autoNumeric.js"></script>
<script>
$('#price').autoNumeric("init", {
aDec: ".",
aSep: ",",
mDec: "2",
wEmpty: "zero",
vMin: "0.00",
vMax: "999999999999.99"
});
</script>
You can find detailed information of autoNumeric plugins in http://mozduljra.hu/szkriptek/autonumeric/ link.

Html.BeginForm does not work with nested forms

View1
#model WebApplication2.Models.TestViewModel
#using (Html.BeginForm("Test", "Home"))
{
<div>Upper form</div>
#Html.EditorForModel()
}
In EditorTemplates i have editor for this view
#model WebApplication2.Models.TestViewModel
#using (Html.BeginForm("Test2", "Home"))
{
<h2>TestViewModel</h2>
}
The actual result is
<form action="/Home/Test" method="post">
<div>Upper form</div>
<div class="editor-label"><label for="Age">Age</label></div>
<div class="editor-field"><input class="text-box single-line" data-val="true" data-val-number="The field Age must be a number." data-val-required="The Age field is required." id="Age" name="Age" type="number" value="0"> <span class="field-validation-valid" data-valmsg-for="Age" data-valmsg-replace="true"></span></div>
<div class="editor-label"><label for="Name">Name</label></div>
<div class="editor-field"><input class="text-box single-line" id="Name" name="Name" type="text" value=""> <span class="field-validation-valid" data-valmsg-for="Name" data-valmsg-replace="true"></span></div>
</form>
But the desire result should be
<form action="/Home/Test" method="post">
<div>Upper form</div>
<form action="/Home/Test2" method="post">
<div class="editor-label"><label for="Age">Age</label></div>
<div class="editor-field"><input class="text-box single-line" data-val="true" data-val-number="The field Age must be a number." data-val-required="The Age field is required." id="Age" name="Age" type="number" value="0"> <span class="field-validation-valid" data-valmsg-for="Age" data-valmsg-replace="true"></span></div>
<div class="editor-label"><label for="Name">Name</label></div>
<div class="editor-field"><input class="text-box single-line" id="Name" name="Name" type="text" value=""> <span class="field-validation-valid" data-valmsg-for="Name" data-valmsg-replace="true"></span></div>
<form>
</form>
So my question is how can i nested the second BeginForm correctly ?
As other mentioned in the comments,nested forms are not a good idea.
What you should be doing is, Keep the form tag for your outer view as it is. For your model, Use normal html form elements without a form tag and use ajax to post data to the server from your java script and once you receive the data, you should be able to access the DOM elements using jQuery and update values as needed.
Something like this ( The below code won't work with the markup you provided. This is just to give you an idea how to handle it generally);
$(function(){
$(document).on("click","#SomeBtnOnModelDialog",function(e){
//Some submit button on model dialog was clicked
e.preventDefault();
//Read the data from model dialog elements using jquery
// and build an object to send to action method
var dummyDataYouWantToSend = { name : "Read it using jquery",age:12};
$.post("#Url.Action("SomeActionMethod","YourController")", dummyDataYouWantToSend ,
function (res){
//Got some response.
//Now update some DOM elemets from the JSON response came back?
// $("#SomeFormElementId").val(res.SomePropertyName);
});
});
});

Posting List<Object> to a webapi 2

I have created a webapi as follow
public OatherResponse Post([FromBody] List<Oather> oather)
{
Note that OatherResponse and Oather both are classes having some property.
Now I am trying to test this using simple html as below
<form method="post" action="http://localhost:50813/api/RegisterOather">
<input type="text" name="oather[0].OatherName" id="oather[0].OatherName" value="a3VsZGVlcA==" />
<input type="text" name="oather[1].OatherName" id="oather[1].OatherName" value="a3VsZGVlcA==" />
<input type="submit" value="Click Here" />
</form>
OatherName is a string property in Oather class. But I always get count of oather as zero.
Am I missing something.
The name attribute values should be
name="[0].OatherName"
name="[1].OatherName"

getting data from upload-template in jquery file upload plugin

I tried to use ASP.NET MVC 3 example of jquery file upload plugin. I've changed upload-template that it shows an input filed and a checkbox for every file (user can set some data for each chosen file). And now when user decides to upload file I need to get not only data provided by plugin (file name, file url, file size) but also data from input and checkbox. But I don't know how to get values when user uploads many files, because if I give an id to these fields there will be the same id for each input and each checkbox, so it's not gonna work. If I give the same class for these fields I can get elements by class and iterate through these fields but I don't know which iteration refers to which file.
I've put hidden inputs in form which is send when file is uploaded but I have no idea how to get data from each input in upload-template to send it via form.
There is a code used to display each file added to queue but not uploaded yet.
<!-- The template to display files available for upload -->
<script id="template-upload" type="text/x-tmpl">
{% for (var i=0, file; file=o.files[i]; i++) { %}
{% var nodeName = file.name.substring(0, file.name.length - 4); %}
<tr class="template-upload fade">
**<td><input id="setNodeName" value="{%=nodeName%}" type="text" class="form-control nodename" /></td>**
{% if (file.error) { %}
<td class="error" colspan="2"><span class="label label-important">{%=locale.fileupload.error%}</span> {%=locale.fileupload.errors[file.error] || file.error%}</td>
{% } else if (o.files.valid && !i) { %}
<td>
<div class="progress progress-success progress-striped active"><div class="bar" style="width:0%;"></div></div>
</td>
<td class="start">{% if (!o.options.autoUpload) { %}
<button class="btn btn-primary">
<i class="icon-upload icon-white"></i>
<span>{%=locale.fileupload.start%}</span>
</button>
{% } %}</td>
{% } else { %}
<td colspan="2"></td>
{% } %}
<td class="cancel">{% if (!i) { %}
<button class="btn btn-warning">
<i class="icon-ban-circle icon-white"></i>
<span>{%=locale.fileupload.cancel%}</span>
</button>
{% } %}</td>
</tr>
{% } %}
</script>
Then there is form which is send when file is uploaded. I added here hidden input to store data from user (input filed which has id setNodeName):
<form id="fileupload" action="#Url.Action("UploadFiles")" method="POST" enctype="multipart/form-data">
**<input type="hidden" id="nodename" value="" />**
<!-- The fileupload-buttonbar contains buttons to add/delete files and start/cancel the upload -->
<div class="row fileupload-buttonbar">
<div class="span7">
<!-- The fileinput-button span is used to style the file input field as button -->
<span class="btn btn-success fileinput-button">
<i class="icon-plus icon-white"></i>
<span>Add files...</span>
<input type="file" name="files[]" multiple>
</span>
<button type="submit" class="btn btn-primary start">
<i class="icon-upload icon-white"></i>
<span>Start upload</span>
</button>
<button type="reset" class="btn btn-warning cancel">
<i class="icon-ban-circle icon-white"></i>
<span>Cancel upload</span>
</button>
<button type="button" class="btn btn-danger delete">
<i class="icon-trash icon-white"></i>
<span>Delete</span>
</button>
<input type="checkbox" class="toggle">
</div>
<div class="span5">
<!-- The global progress bar -->
<div class="progress progress-success progress-striped active fade">
<div class="bar" style="width:0%;"></div>
</div>
</div>
</div>
<!-- The loading indicator is shown during image processing -->
<div class="fileupload-loading"></div>
<br>
<!-- The table listing the files available for upload/download -->
<table class="table table-striped"><tbody class="files" data-toggle="modal-gallery" data-target="#modal-gallery"></tbody></table>
</form>
And in the function called before the file is uploaded I wanted to transfer data from input in upload-template to hidden input in form. And as I said I tried to call it by id but when there is more than one file I have a couple of inputs with the same id so it's not working. I also tried to get elements by class (I changed setnodename id to setnodename class) and I had a couple of inputs with data from user but I didn't know which of these inputs should I use at the moment because files in jquery plugin don't have index value. So for each uploaded file I had an array of inputs (count of inputs was equal to added files count) but I didn't know which of array elements is valid for file which was uploaded at the moment.
I think you should take a look at the documentation of plugin about sending additional parameters with file. What you would need to do is to add event handler on 'fileuploadsubmit' which will fire on every file before it uploads:
$('#fileupload').bind('fileuploadsubmit', function (e, data) {
var inputs = data.context.find(':input');
data.formData = inputs.serializeArray();
})

Categories