jQuery Validate multiple extensions - javascript

I am using https://github.com/DiegoLopesLima/Validate this validation plugin to validate the form
I added extensions and I want to use 2 extension rule in one field
Something like this
'data-validate' => ' max , min ', // in field
jQuery.validateExtend({
min: {
conditional: function(value) {
return false;
}
},
max: {
conditional: function(value) {
return false;
}
}
});
Here is example how use in one rule I want multiple rules
<form>
<input type="text" name="age" data-validate="age" />
</form>
jQuery('form').validate();
jQuery.validateExtend({
age : {
required : true,
pattern : /^[0-9]+$/,
conditional : function(value) {
return Number(value) > 17;
}
}
});

This may not exactly be the answer you are looking for but this can be done in pure HTML. The drawback is that it requires a modern browser (IE10, Chrome, Firefox etc.) to be used. The advantage is that its much easier to use and works without JS.
Check out:
https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Forms/Data_form_validation
Specifcally for what you need, go here and look at the "How old are you" input example:
https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Forms/Data_form_validation#Other_validation_constraints
<input type="number" min="12" max="120" step="1" id="n1" name="age" pattern="\d+">
Looking at your code you are looking for a required age input where the value must be greater than 17, this would be for example:
<input type="number" min="18" id="age" name="age" pattern="\d+" required>
Hopefully this helps a little.

Related

How to force the user to put only numbers

I want the user to only be able to use input for numbers I've tried several things like oninput="this.value = this.value.replace(/[^0-9.]/g, '') and a lot more but for example the code I sent if I type a letter and keep pressing the letter on the keyboard it won't turn it to anything, I need a code that will 100% force the user to type only numbers doesn't matter what happens. if I could put a number in the input box that the user cant delete for example 0 it will be good to.
There are a few different ways to accomplish this but one of them would be capturing the keypress itself and returning false if the input is not a number.
Also if I understand you correctly, to add a default value of "0", just define it in the input directly like value="0", or you could use a placeholder="0" if that's what you're looking for.
<input type="number" value="0" onkeydown="javascript: return event.keyCode === 8 || event.keyCode === 46 ? true : !isNaN(Number(event.key))" />
You can use <input type=...> as mentioned in the input specification.
While this wouldn't enforce the user input to numbers only, you may want to consider using the pattern attribute to leverage some built-in behaviour. If you type non-numeric characters, the text colour will turn red:
input:invalid {
color: red;
}
<input type="text" pattern="[0-9]+"/>
Then we can start looking at the constraint validation API:
The Constraint Validation API enables checking values that users have entered into form controls, before submitting the values to the server.
If you type non-numeric characters and try to submit the form, you should see a built-in tooltip displaying a custom error message:
const input = document.querySelector('input');
input.addEventListener('invalid', () => {
if (input.validity.patternMismatch) {
input.setCustomValidity('Numbers only please!!');
}
});
input:invalid {
color: red;
}
<form>
<input type="text" pattern="[0-9]+"/>
<button type="submit">submit</button>
</form>
$("#but").click(function(){
let inp_val = $("#txt").val();
if(isNaN(inp_val)){
alert("Just enter a number.");
$("#txt").val("");
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="txt">
<input type="button" value="CLICK" id="but">

How to use hasOwnProperty with AngularJS Directive `attrs` object

I have a directive named ip-abc which is used to check the input values of fields and convert to dollar formatted values. I have a condition where if we have the value as "0", then I will convert that to $0.
ipabc.js
var filterFunc = function (value) {
if(value == '0'){
if(attrs.hasOwnProperty('ipZeroDollar')){
var currencyValue = $filter('currency')(value);
currencyValue = currencyValue.toString();
return currencyValue.replace('.00','');
}
}
The problem which I am facing is that, how can I set ipZeroDollar = true in HTML. As of now, (attrs.hasOwnProperty('ipZeroDollar')) is coming as false.
<div ng-class = {'//something'}
<input type="tel" name="amount" class="form-control" ng
model="Data.Amount" maxlength="15" required ip-abc/>
</div>
The problem which I am facing is that, how can I set ipZeroDollar = true in HTML. As of now, (attrs.hasOwnProperty('ipZeroDollar')) is coming as false.
The camelCase needs to be normalized to kebab-case in the HTML:
<input type="tel" name="amount" class="form-control"
ng-model="Data.Amount" maxlength="15" required
ip-abc ip-zero-dollar />
For more information, see
AngularJS Developer Guide - Attribute Normalization
AngularJS attrs Type API Reference
The DEMO
angular.module("app",[])
.directive("ipAbc", function() {
return {link: postLink};
function postLink(scope,elem,attrs) {
var hasIpZeroDollar = attrs.hasOwnProperty("ipZeroDollar");
console.log("hasIpZeroDollar",hasIpZeroDollar);
}
})
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app"
<input type="tel" name="amount" class="form-control"
ng-model="Data.Amount" maxlength="15" required
ip-abc ip-zero-dollar />
</body>
This is how you use hasOwnProperty().
let obj = {color: 'yellow'}
obj.hasOwnProperty('color') // returns true
It seems like you would want to call hasOwnProperty() on Data since that looks like its an object, and that is where you are getting the amount.

Assign v-validate multiple validation rules (predefined and custom)

I can't figure out how to assign multiple rules to vee-validate. Usualy you pipe | the rules inside v-validate attribute, but the problem is that I also try to include one custom method.
<input id="number" type="tel" v-model="cardDetail.number" v-card-focus
class="form__input"
v-validate="'required'" <!-- need to add requireNumberIfCreditCard method -->
data-vv-validate-on="blur"
name="number" required>
<label for="number" class="form__label">
{{ $root.trans.translate('cardNumber') }}
</label>
<p class="form__error" v-show="errors.has('number')">
{{ errors.first('number') }}
</p>
This is my javascript
export default {
data() {
return {
cardDetail: {
number: '',
}
}
},
computed: {
requireNumberIfCreditCard() {
if (this.paymentMethod === 'creditCard') {
return this.cardDetail.number ? "required" : "";
}
}
}
};
How should my HTML look like so I will be also able to add custom mthods to vee-validate? If you need any additional informations, please let me know and I will provide. Thank you!
The attribute v-validate is bound to your data, so you can use anything you want within it. Further, it supports different syntaxes - one, which you're using is a string (i.e. 'required'). Another form it supports is an object, which is what you need:
<input id="number" type="tel" v-model="cardDetail.number" name="number"
v-validate="{ required: (requireNumberIfCreditCard == 'required') }">
I recommend you change your computed value to return true/false, in which case you can just use it directly.
Working example: https://codesandbox.io/s/km4lw12823

Limit the user's input in an input number to 4 digits

How can I prevent (usign maybe Angular) the user from entering more than 4 numbers in a an simple number like this one :
<input type="number">
I used ng-maxlength, and max attributes, but those attributes as specified by w3.org specs and the official website Angular, do not prevent the user from adding more numbers.
What I want is that the input stops in 4 digits, like adding in somehow a mask or something to it.
Here is a way to do it using JavaScript:
HTML
<input type="number" oninput="checkNumberFieldLength(this);">
JavaScript
function checkNumberFieldLength(elem){
if (elem.value.length > 4) {
elem.value = elem.value.slice(0,4);
}
}
I would also suggest to make use of the min and max HTML attributes for the input Number element, if it applies in your case.
JSFiddle
W3c: input Number
Well, as somebody stated above maxlength doesn't work with inputs of type number, so you can do it this way:
<input type="text" pattern="\d*" maxlength="4">
of course, this will do if it's not a requirement to have input type="number"
Using ng-pattern with a regex
\d : digits
{4} : 4 times
<input type="number" ng-pattern="/^\d{4}$/" />
I would create a function in your controller like this
angular.module("my-app", [])
.controller('my-controller', function($scope) {
$scope.checkInput = function() {
if (input.value.length > 4) {
input.value = input.value.slice(0,4);
}
});
});
Then in your view you can do something like this
<input type="number" max="9999" ng-input="checkInput()" />
Warning: The max attribute will only work for the spinner. The user will still be able to enter numbers higher than that. Here's an example
<input type="number" max="9999" />
You can do that using modernizr and jquery.
I've made an example here: https://jsfiddle.net/5Lv0upnj/
$(function() {
// Check if the browser supports input[type=number]
if (Modernizr.inputtypes.number) {
$('input[type=number]').keypress(function(e) {
var $this = $(this),
maxlength = $this.attr('maxlength'),
length = $this.val().length;
if (length >= maxlength)
e.preventDefault();
});
}
});

Why 1. returns an empty string when I try to get value of an input type number using javascript and html5?

I have a normal input as follows:
<input type="number" name="quantity" id="myInput">
If I type "1." (without the quotes of course) when I try to get the value of the input with
document.getElementById("myInput").value
Only an empty string is obtained.
Is there any other way to get the "1." input with javascript?
Edit
I am working using Polymer 1.0 and databinding, so in my example I showed using normal JavaScript syntax with the intention of finding a solution to my problem using only javascript.
I just want to know how to access a property that returns the value of the input, and which I believe should be stored in some property of the object.
If you use <input type="number"> the element is enriched with an extra attribute, valueAsNumber. So instead of
document.getElementById("myInput").value
use
document.getElementById("myInput").valueAsNumber
valueAsNumber will return NaN instead of blank if the value entered in the input not is convertable to a number. There is also a validity attribute holding information of the status of the current value, both according to the value as supposed number but also according to the number input's settings, i.e "why is the number invalid".
Fun with number inputs, try this out in various browsers :
<input type="number" name="quantity" id="myInput" ><br>
<input type="text" id="value" ><br>
<input type="text" id="valueAsNumber" ><br>
<input type="text" id="validity" ><br>
document.getElementById("myInput").onkeyup = function() {
document.getElementById("value").value = this.value;
document.getElementById("valueAsNumber").value = this.valueAsNumber;
document.getElementById("validity").value = '';
for (validity in this.validity) {
if (this.validity[validity]) {
document.getElementById("validity").value+=validity+' ';
}
}
}
actually quite informative, if you want to investigate exactly why you get an empty value back from the input -> http://jsfiddle.net/oaewv2Lr/ Have tried with Chrome, Opera and FF - Chrome seems to be the most "forgiving" browser of those three.
I found a way to get invalid values:
Focus the input.
Select its contents using execCommand().
Grab the selection using window.getSelection().
Example:
document.querySelector('input[type="submit"]').addEventListener('click', function() {
var inp= document.getElementById('myInput');
inp.focus();
document.execCommand('SelectAll');
var value = window.getSelection().toString();
document.getElementById('output').textContent = value;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" name="quantity" id="myInput">
<input type="submit">
<div id="output"></div>
It won't work if you will enter 1., as 1. is not a valid number.
Update: It seems that your use of type="number" means that certain values won't come back. You can switch it to a type="text" and do the checking yourself:
document.getElementById('mySubmit').addEventListener('click', function() {
var value = document.getElementById('myInput').value;
if ( value != parseFloat(value) )
alert('Invalid Number');
document.getElementById('myOutput').innerHTML = value;
});
<input type="text" name="quantity" id="myInput">
<input type="submit" id="mySubmit">
<div id="myOutput"></div>

Categories

Resources