I have an input element with a minRange and maxRange set and am trying to get a custom validity message. I also have a Input TagHelper to write a custom message that I am trying to override on client-side.
I have tried this so far and it doesn't seem to be working.
<input asp-for="Amount" minRange="50.00" maxRange="100.00" oninput="check(this)" />
<script type="text/javascript">
function check(input) {
if (input.validity.rangeUnderflow || input.validity.rangeOverflow) {
input.setCustomValidity("Please enter an amount between $50.00 and $100.00.");
}
}
</script>
Rendered html:
<input oninput="check(this)" type="text" data-val="true" data-val-number="The field Amount must be a number." data-val-required="The Amount field is required." id="Model_Amount" name="Model.Amount" value="97.95" data-val-range-min="50.00" data-val-range-max="100.00" data-val-range="Please enter an Amount between 50.00 and 100.00" class="form-control valid" placeholder="Amount" aria-required="true" aria-invalid="false" aria-describedby="Model_Amount-error">
It still inputs "Please enter Amount between 50.00 and 100.00"
input taghelper:
public override void Process(TagHelperContext context, TagHelperOutput output)
{
if (MinRange != null && MaxRange != null)
{
TagHelperAttribute minAttr = new TagHelperAttribute("data-val-range-min", MinRange);
output.Attributes.Add(minAttr);
TagHelperAttribute maxAttr = new TagHelperAttribute("data-val-range-max", MaxRange);
output.Attributes.Add(maxAttr);
TagHelperAttribute rangeAttr = new TagHelperAttribute("data-val-range", string.Format("Please enter a {0} between {1} and {2}", DisplayName, MinRange, MaxRange));
output.Attributes.Add(rangeAttr);
}
}
Any help is appreciated.
Thanks
NH
Changed your code with some comments added. Hope this helps
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<!-- Change minRange/maxRange to just min/max -->
<input asp-for="Amount" min="50.00" max="100.00" oninput="check(this)" />
<span id="display"></span>
</body>
<script type="text/javascript">
function check(input) {
//Get current input field value
var num = parseInt(document.querySelector('input').value);
//Check if num is < or > than input.min/max
if(num >= input.min && num <= input.max){
document.getElementById('display').innerText = '';
}else{
document.getElementById('display').innerText = 'Number must be between 50 and 100';
}
}
</script>
</html>
Related
Hey I'm trying to figure out what is wrong with my code. The code is supposed to validate password with the requirement of having few special characters and setting its minimum length.
I got it to set on the right length but I can't seem to get the directive file working.
app.directive('myPassord',function()
{
return{
require:'ngModel',
link:function(scope,element,attr,myFormCtrl){
function myValidation(value)
{
if (value.indexOf("$") > -1 || value.indexOf("%") > -1 || value.indexOf("^") > -1 || value.indexOf("&") > -1 || value.indexOf("*") > -1){
myCtrl.$setValidity('Charactervalidator', false);
}else{
myCtrl.$setValidity('Charactervalidator', false);
}
return value;
}
myFormCtrl.$parsers.push(myValidation);
}
}
});
The html file
<div ng-controller = "myFormCtrl" class="form-group">
<form name ="Form1" novalidate="novalidate" class="Form1">
<p>
<label for = "password1" class= "col-lg-2">Password</label>
<input type="text" name="Password1" ng-model="user.password" ng-minlength ="8" required data-my-password>
<span ng-show="Form1.Password1.$touched && Form1.Password1.$invalid" style="color:red"> Password must contain at least 8 characters and a special character</span>
</p>
</form>
</div>
I correct your code. Try this code. Hope this helps you
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body ng-app="myApp">
<div class="form-group">
<form name="Form1" novalidate="novalidate" class="Form1">
<p>
<label for="password1" class="col-lg-2">Password</label>
<input type="text" name="Password1" ng-model="user.password" ng-minlength="8" required my-password>
<span ng-show="Form1.Password1.$touched && Form1.Password1.$invalid" style="color:red">
Password must contain at least 8 characters and a special character</span>
</p>
</form>
</div>
<h1>{{myForm.myInput.$valid}}</h1>
<script>
var app = angular.module('myApp', []);
app.directive('myPassword', function() {
return {
require: 'ngModel',
link: function(scope, element, attr, myFormCtrl) {
function myValidation(value) {
if (value.indexOf("$") > -1 ||
value.indexOf("%") > -1 ||
value.indexOf("^") > -1 ||
value.indexOf("&") > -1 ||
value.indexOf("*") > -1) {
myFormCtrl.$setValidity('Charactervalidator', true);
} else {
myFormCtrl.$setValidity('Charactervalidator', false);
}
return value;
}
myFormCtrl.$parsers.push(myValidation);
}
}
});
</script>
</body>
</html>
I have a pretty simple calculator that I am trying to setup.
<!DOCTYPE html>
<p>Crypto Currency Diversifier</p>
<div class="container">
<h1>Crypto Currency Diversifier</h1>
<form action="/action_page.php">
Dollars:<br>
<input type="text" name="dollars" value="500"><br><br>
# of Currencies:<br>
<input type="text" name="quantity" value="20"><br><br>
<input type="submit" value="Submit">
</form>
The next step is I need to pull the top 20 (quantity) cryptocurrencies, then divide the 500 (dollars) between them relative to market cap.
Here's the API website: https://coinmarketcap.com/api/
Clicking on https://api.coinmarketcap.com/v1/ticker/?limit=10 shows me the top 10 currencies.
How can I ADD up all the market caps of each individual currency on the page. Then create ratios from them?
Math part is pretty straightforward, what I don't get is how to actually pull the data from the API link and get it in a workable format.
Lookup Jquery and Ajax:
You can implement this like this:
function getCurrencies()
{
$.ajax(
{url:"https://api.coinmarketcap.com/v1/ticker/?limit=20",
success:function(data) {
//console.log(data);
var totalcap=0.0;
var u=$("<ul>");
for(var i=0;i<data.length;i++) {
var currency=data[i];
var cap=parseFloat(currency["market_cap_usd"]);
var li=$("<li />").html(currency["name"] + " " + cap.toFixed(2).replace(/./g, function(c, i, a) {
return i && c !== "." && ((a.length - i) % 3 === 0) ? ',' + c : c;
}));
u.append(li);
totalcap+=cap;
}
$('#currlist').html('').append(u);
$('#cap').html(totalcap.toFixed(2).replace(/./g, function(c, i, a) {
return i && c !== "." && ((a.length - i) % 3 === 0) ? ',' + c : c;
}));
$('#data').val(JSON.stringify(data));
},
error:function() {
alert("Error");
},
dataType:"json",
type:"get"}
);
}
textarea {width:600px;height:250px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<p>Crypto Currency Diversifier</p>
<div class="container">
<h1>Crypto Currency Diversifier</h1>
<form action="/action_page.php">
Dollars:<br>
<input type="text" name="dollars" value="500"><br><br>
# of Currencies:<br>
<input type="text" name="quantity" value="20"><br><br>
<input type="submit" value="Submit" onclick="getCurrencies(); return false"
>
Total Market Cap:<div id="cap"></div><br />
Currencies: <div id="currlist"></div><br />
<textarea id="data"></textarea>
</form>
in AngularJS 1.5 I have a form with an input field of type "time". It works, but the time shown should be HH:mm - without seconds, etc.
Chrome does this by default, but Firefox and Internet Explorer show with seconds and milliseconds (e.g. "14:56:00.000" instead of "14:56").
How can we show the required time format in all browsers?
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example - example-time-input-directive-production</title>
<script src="//code.angularjs.org/snapshot/angular.min.js"></script>
</head>
<body ng-app="timeExample">
<script>
angular.module('timeExample', [])
.controller('DateController', ['$scope', function($scope) {
$scope.example = {
value: new Date(1970, 0, 1, 14, 56)
};
}]);
</script>
<form name="myForm" ng-controller="DateController as dateCtrl">
<label for="exampleInput">Pick a time between 8am and 5pm:</label>
<input type="time" id="exampleInput" name="input" ng-model="example.value"
placeholder="HH:mm" min="08:00" max="17:00" required />
<div role="alert">
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.time">
Not a valid date!</span>
</div>
<tt>value = {{example.value | date: "HH:mm:ss"}}</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/>
</form>
</body>
</html>
Thank you!
Firefox and IE don't support <input type="time">, it's browser dependent. See this link for more info on W3. So your input field will not be able to display it the same way as in Chrome.
An alternative is to use uib-timepickerfrom angular-ui or try one from jquery like webshim.
try using step attribute and set it to 60".
<input type="time" id="exampleInput" name="input" ng-model="example.value"
placeholder="HH:mm" min="08:00" max="17:00" required step="60" />
Date time input types are not supported by IE11 and Safari. But we hope for the best and regularly visit this "can_i_use" link to see if something has changed.
https://caniuse.com/#feat=input-datetime
We can write a common method in controller end to not allow second and millisecond to be shown in input type time
getFormatDate = function (val) { // assuming val is date like "/Date(946673340000)/"
if (val != undefined) {
date = new Date(val.match(/\d+/)[0] * 1); // creating a date object from val
return new Date(date.getFullYear(), date.getMonth(), date.getDate(),
date.getHours(), date.getMinutes());
}
}
I am trying to write a code where the control goes into a block of code only when the text in the input type changes or is cleared. I am using the below condition:
if(myfrm.textchecker.$dirty && !myfrm.textchecker.$pristine)
This doesn't work until I change it to :
if(!myfrm.textchecker.$dirty && !myfrm.textchecker.$pristine)//completely opposite
Here is my code for reference :
<html>
<head>
<script src="angular.min.js"></script>
</head>
<body ng-app="myApp">
<div ng-controller="outerCtrl">
<form name="myfrm">
<input type="password" name="textchecker" ng-change="processed(ngdata)" ng-model="ngdata" required/>
<input type="submit" name="submit" value="submit">
</form>
<span style="color:red" ng-show="myfrm.textchecker.$error.required">please enter the required text</span>
{{ngdata}}
<p>
{{final}}
</p>
<p>
$dirty : {{ myfrm.textchecker.$dirty }} </br>
$invalid : {{myfrm.textchecker.$invalid }}
</br>
$pristine : {{myfrm.textchecker.$pristine }}
</p>
</div>
</body>
</html>
<script>
var app=angular.module("myApp",[]);
app.controller("outerCtrl",function($scope){
$scope.processed=function(password)
{
if(!myfrm.textchecker.$dirty && !myfrm.textchecker.$pristine)
{
console.log('!myfrm.textchecker.$dirty + !myfrm.textchecker.$pristine');
console.log(!myfrm.textchecker.$dirty + !myfrm.textchecker.$pristine);
// var password=$scope.ngdata;
var strength=0;
//console.log(password);
// alert($scope.ngdata);
// if (password.length > 7) strength += 1
//if password contains both lower and uppercase characters, increase strength value
if (password.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/)) strength += 1
//if it has numbers and characters, increase strength value
if (password.match(/([a-zA-Z])/) && password.match(/([0-9])/)) strength += 2
//if it has one special character, increase strength value
if (password.match(/([!,%,&,#,#,$,^,*,?,_,~])/)) strength += 3
//if it has two special characters, increase strength value
if (password.match(/(.*[!,%,&,#,#,$,^,*,?,_,~].*[!,%,&,#,#,$,^,*,?,_,~])/)) strength +=5
//now we ha
if(strength<=2)
{
$scope.final="Poor";
}
else
if(strength>2 && strength<=5)
{
$scope.final="Weak";
}
else
if(strength>5 && strength<=9)
{
$scope.final="Good";
}
if(strength>9)
{
$scope.final="Strong";
}
}
}
});
</script>
In order to use the $dirty & $pristine of your form in your controller you have to access them with $scope.
if ($scope.myfrm.textchecker.$dirty && !$scope.myfrm.textchecker.$pristine) {
var app = angular.module("myApp", []);
app.controller("outerCtrl", function($scope) {
$scope.processed = function(password) {
if ($scope.myfrm.textchecker.$dirty && !$scope.myfrm.textchecker.$pristine) {
console.log('!myfrm.textchecker.$dirty + !myfrm.textchecker.$pristine');
console.log(!myfrm.textchecker.$dirty + !myfrm.textchecker.$pristine);
// var password=$scope.ngdata;
var strength = 0;
//console.log(password);
// alert($scope.ngdata);
// if (password.length > 7) strength += 1
//if password contains both lower and uppercase characters, increase strength value
if (password.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/)) strength += 1
//if it has numbers and characters, increase strength value
if (password.match(/([a-zA-Z])/) && password.match(/([0-9])/)) strength += 2
//if it has one special character, increase strength value
if (password.match(/([!,%,&,#,#,$,^,*,?,_,~])/)) strength += 3
//if it has two special characters, increase strength value
if (password.match(/(.*[!,%,&,#,#,$,^,*,?,_,~].*[!,%,&,#,#,$,^,*,?,_,~])/)) strength += 5
//now we ha
if (strength <= 2) {
$scope.final = "Poor";
} else
if (strength > 2 && strength <= 5) {
$scope.final = "Weak";
} else
if (strength > 5 && strength <= 9) {
$scope.final = "Good";
}
if (strength > 9) {
$scope.final = "Strong";
}
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller="outerCtrl">
<form name="myfrm">
<input type="password" name="textchecker" ng-change="processed(ngdata)" ng-model="ngdata" required/>
<input type="submit" name="submit" value="submit">
</form>
<span style="color:red" ng-show="myfrm.textchecker.$error.required">please enter the required text</span>
{{ngdata}}
<p>
{{final}}
</p>
<p>
$dirty : {{ myfrm.textchecker.$dirty }} $invalid : {{myfrm.textchecker.$invalid }} $pristine : {{myfrm.textchecker.$pristine }}
</p>
</div>
</body>
I'm trying to write this extremely simple javascript app where the user can input two numbers and the sum of these two is automatically outputted to screen. I'm very new to javascript so I'm not sure where I went wrong. The following code will print NaN for a second after I press the button. Any idea as to how I handle this input better?
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction()
{
var x = parseInt(first_num);
var y = parseInt(second_num);
var z = x + y;
var a = z.toString();
document.getElementById("demo").innerHTML = a;
}
</script>
</head>
<body>
<p>Enter two numbers to be added together.</p>
<form>
<input id="first_num" name="first_num" > first num<br>
<input id="second_num" name="second_num" > second num
<button onclick="myFunction()">calculate</button>
<p id="demo"></p>
</body>
</html>
var x = parseInt(first_num);
var y = parseInt(second_num);
Instead of first_num and second_num, you need to retrieve the value from the input boxes, like this
var x = parseInt(document.getElementById("first_num").value);
var y = parseInt(document.getElementById("second_num").value);
You have to use a selector to get the value of the two input elements:
var x = parseInt(document.getElementById('first_num').value);
var y = parseInt(document.getElementById('second_num').value);
...
And you have to close your form tag in your HTML use and use a <input type="button"> instead of <button> so your form doesn't post unnecessarily.
<form>
<input id="first_num" name="first_num" > first num <br />
<input id="second_num" name="second_num" > second num <br />
<input type="button" onclick="myFunction()" value="calculate">
</form>
Here is working demo.
The reason of NaN is you trying to parseInt with not initialized variable. beside this input tag is not closed.
function myFunction() {
document.getElementById("demo").innerHTML = parseInt(document.getElementById('first_num').value) + parseInt(document.getElementById('second_num').value);
}
and html:
<p>Enter two numbers to be added together.</p>
<input id="first_num" name="first_num" />first num
<br>
<input id="second_num" name="second_num" />second num
<button onclick="myFunction()">calculate</button>
<p id="demo"></p>
Here is a working sample:
<!DOCTYPE html>
<html>
<head>
<title>Page</title>
</head>
<body>
<p>Enter two numbers to be added together.</p>
<input id="first_num" name="first_num">first num<br />
<input id="second_num" name="second_num">second num<br />
<button onclick="myFunction()">calculate</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.getElementById("first_num").value;
var y = document.getElementById("second_num").value;
var z = ((x && x != "") ? parseInt(x) : 0) + ((y && y != "") ? parseInt(y) : 0);
document.getElementById("demo").innerHTML = z;
}
</script>
</body>
</html>
Do the following:
<p>Enter two numbers to be added together.</p>
<form>
<input id="first_num" name="first_num" > first num<br>
<input id="second_num" name="second_num" > second num
<button onclick="myFunction(parseInt(document.getElementById("first_num").value),parseInt(document. getElementById("second_num").value))">calculate</button>
<p id="demo"></p>
function myFunction(first_num,second_num)
{
var x = parseInt(first_num);
var y = parseInt(second_num);
var z = x + y;
var a = z.toString();
document.getElementById("demo").innerHTML = a;
}