HTML5 + JavaScript, type of input - javascript

When I declare JS.
var test = $("#test").val();
Then the "number validaion" is not working on the browser side.
<input type="number" id="test" name="test" required>
Is there any chance to declare $("#test") and use HTML5 in input validation as well (such as required, number validation etc.)? Or I have to to do it on JS side.
It have to be declared to use it later in my AJAX post scipt.
Thanks :)

Use parseInt("stringOfNumber") to get integer from string. When inputting data, you write strings, not numbers.

This is how you use the input type number in HTML5:
<input type="number" name="cost">
Here is a working example of the http://www.w3schools.com/html/tryit.asp?filename=tryhtml5_input_type_number.
If you want to add validation try this:
<input type="number" pattern="[0-9]*" name="cost">
Here is a working example of the pattern attribute http://www.w3schools.com/html/tryit.asp?filename=tryhtml5_input_pattern
Note: Both the input type number and the pattern attribute have limited browser support.

You can check if it's Not a Number, and then invert it.
if(!isNaN(test))
{
// Is a number
}
If you use jQuery, you could use
if($.isNumeric(test))
{
// Is a number
}
Don't rely on Client Side validation though, as it can be easily avoided and some browsers don't support it. E.g: JavaScript validation can be avoided by disabling JavaScript.

Related

characters in field

I've been doing a lot of research on this and still can't find a good solution. Basically, I have this field in my form that should ONLY allow numbers. However, I'm able to enter mac special characters inside that field by doing:
Hold down option + shift and then pressing any button from keyboard (example: h j k l u i , etc).
Please see attached picture.
Can anyone help me on NOT allowing such characters inside the ID field? Thanks a lot in advance!
Here's my code:
LIVE DEMO
ID: <input formControlName="userid" type="text" pKeyFilter="num" placeholder="Numbers" pInputText>
There are many approaches to this problem. All of the provided solutions should work. My recommendation is Approach 2.
Approach 1
You can try to remove non number characters on the input event like this
<input
formControlName="userid"
type="text"
placeholder="Numbers"
oninput="javascript: this.value = this.value.replace(new RegExp('[^0-9]', 'gm'), '')"
pInputText
/>
Modified Demo
I tested this in Firefox and Chrome on MacOS and it seems to work fine.
Approach 2
To do this from your angular module:
Use a simple text input
<input
formControlName="userid"
type="text"
placeholder="Number"
pInputText
/>
Listen to changes and patch the value accordingly. Don't forget to register your observers on init.
registerChangeObservers() {
this.registrationFormGroup.get("userid").valueChanges.subscribe(val => {
this.registrationFormGroup.patchValue({
'userid': val.replace(new RegExp('[^0-9]', 'gm'), '')
}, { emitEvent: false });
});
}
ngOnInit() {
this.registerChangeObservers();
}
Especially note the { emitEvent: false } part. You need to set this to avoid recursion. This approach can fail if your model becomes invalid and therefore it's value changes to nil. For example this can happen if you set your input type to number, but a user manages to input a non number character. To avoid this make sure the input validation doesn't fail on special characters, e.g. by setting the input type to text.
Demo here
Approach 3
To avoid the display of modifying characters you can also listen to input events (i.e. key presses) instead of actual value changes. This is equivalent to approach 1.
To do so use this input
<input
formControlName="userid"
type="text"
placeholder="Number"
pInputText
(input)="onPress($event)"
/>
and add this function to your controller
onPress($event) {
this.registrationFormGroup.patchValue({
'userid': $event.target.value.replace(new RegExp('[^0-9]', 'gm'), '')
}, { emitEvent: false });
}
Demo 3
Note: I would generally avoid this approach because in my experience the suppression of modifying characters can have unintended side effects with some uncommon input methods, especially on mobile. The approach above (Approach 2) also works and is safer in my opinion. Although modifying characters are displayed, they will disappear on the next user action and will never be present in your model data.
You have already tried with:
<input type="number" pattern="[0-9]{10}" />
the following validates a 10-digit number, and I also think you should do a validation with JavaScript:
<input type="text" id="text" onblur="validaNumericos();" />
Function Javascript:
function validaNumericos(){
var inputtxt = document.getElementById('text');
var valor = inputtxt.value;
for(i=0;i<valor.length;i++){
var code=valor.charCodeAt(i);
if(code<=48 || code>=57){
inputtxt.value="";
return;
}
}
}
<input type="text" id="text" onblur="validaNumericos();" />
Use input type=number.
ID: <input formControlName="userid" type="number" pKeyFilter="num" placeholder="Numbers" pInputText>
If you don't like the dial controls on the right side, you can disable them with this in your css:
input[type=number]::-webkit-inner-spin-button {
-webkit-appearance: none;
}
input[type=number] {
-moz-appearance:textfield;
}
Here is a fork of your demo with all the changes.
Well, if you are looking for a regex answer (based on your tag), you can test on the length of the pre-regex value vs. the length of the post regex value.
if there are extra characters, the lengths will not match.
[0-9]+

jquery form validation allow only standard USA numbers

I found this plugin good so far Jquery Form Validator as so far it has fulfilled all my requirements but i am stuck to set validation for the users to enter only USA mobile number format something like this 1-(XXX)-XXX-XXXX . It should allow only this number to enter else it should not accept and should show form validation error.
I have researched but unable to find any tutorial or demo code which is showing how to achieve this particular thing and hence i had to put this question.
Can someone guide me or show me some code if possible how to achieve this using data-* attributes in html tags (i.e. <input data-validation="creditcard" data-validation-allowing="visa, mastercard, amex">) or any other way with the help of utilizing this plugin..
I am trying to utilize this Configuration Callbacks but i am bit confused how to utilize this as i have multiple forms and i have only put this code in my common.js file for all the forms which works well using for all the forms.
$.validate({
modules : 'security, file'
});
So i want something like common data-* attribute (if its available) which can work in a parcular html form which can be feasible for me as i do not need to type different code based on different form like this $.validate({form : '#LoginForm'}); as above common method will be feasible for me ..
Can someone help me to achieve this thing please ?
Any help will be highly appreciated.
Thanks.
Eventually I have sorted out this thing with ease thanks to #mplungjan who provided me a link and shown me a way how to accomplish this.
I simply went here to the library Default validation custom and I see they actually are providing the facility to make regex validation on the go ..
I searched regex to check US mobile numbers Phone Number Regex US
And then after finding a regex to work with, I used this HTML code,
<input name="user_mobile_no" class="form-control error" placeholder="Mobile No."
data-validation="required custom"
data-validation-error-msg-required="Please Enter Mobile Number"
data-validation-regexp="\D*([2-9]\d{2})(\D*)([2-9]\d{2})(\D*)(\d{4})\D*"
data-validation-error-msg-custom="Invalid Mobile Number (i.e. +1 XXX-XXX-XXXX)"
maxlength="50" id="user-mobile-no" value="+1 215-555-1212"
style="border-color: rgb(185, 74, 72);" type="text">
And voila, its working.
Notice these lines I have put above, data-validation="required custom" custom is required to put there to make custom validation.
Then after I put
data-validation-regexp="\D*([2-9]\d{2})(\D*)([2-9]\d{2})(\D*)(\d{4})\D*"
which checks valid phone numbers and last but not the least, i have put two different validation error messages to show to the users for required data-validation-error-msg-required="Please Enter Mobile Number" and invalid number data-validation-error-msg-custom="Invalid Mobile Number (i.e. +1 XXX-XXX-XXXX)" .
Thanks guys for support. I hope it helps someone who needs to deal with similar thing. Really appreciated.
Thank you.
/*
It works for these number formats:
1-234-567-8901
1-234-567-8901 x1234
1-234-567-8901 ext1234
1 (234) 567-8901
1.234.567.8901
1/234/567/8901
12345678901
1-234-567-8901 ext. 1234
(+351) 282 433 5050
*/
jQuery.validator.addMethod("usPhoneFormat", function (value, element) {
return this.optional(element) || /^\(*\+*[1-9]{0,3}\)*-*[1-9]{0,3}[-. /]*\(*[2-9]\d{2}\)*[-. /]*\d{3}[-. /]*\d{4} *e*x*t*\.* *\d{0,4}$/.test(value);
}, "Enter a valid phone number.");
$(document).ready(function(){
$("#sampleForm").validate({
rules: {
phoneNumberRegEx: {
usPhoneFormat: true,
required: true
}
},
submitHandler: function (form) {
alert("submitted.");
}
});
$(".phone").mask("0-000-000-0000", {placeholder: "_-___-___-____"});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.15.0/jquery.validate.min.js"></script>
<script type="text/javascript" src="http://igorescobar.github.io/jQuery-Mask-Plugin/js/jquery.mask.min.js"></script>
<form id="sampleForm" method="POST">
<fieldset>
<label for="phoneNumberRegEx">Phone: </label>
<input type="text" id="phoneNumberRegEx" name="phoneNumberRegEx" class="phone" />
</fieldset>
<input type="submit" value="Submit" />
</form>
If u wanna have advanced validation with specific series codes, u can try to use data from this package https://www.npmjs.com/package/dialcodes

Handling default form values with jquery.validationEngine.js

I am using jquery.validationEngine.js for form validation .
I was downloaded this js from http://www.position-absolute.com/articles/jquery-form-validator-because-form-validation-is-a-mess/
this site.But it not works for checking validation for default value such as I have first name field whose value is "First Name".I want validation for checking that this field should not be blank but it not works because it contains default value "First Name".
Also I want this should work in jquery.validationEngine.js file because I have to many validations on form & I am using this js.
My field is
<input type="text" id="Uname" name="Uname" value="User Name" onfocus="if(this.value=='User Name')this.value='';" onblur="if(this.value=='')this.value='User Name';" />
If anyone using this file let me know & help to solve this problem.
If you wish to use validationEngine to validate your form the way you describe, there appear to be at least three solutions based on the documentation.
1) You can create a new custom regex in the translation file for each default text value, and then add that custom regex to the relevant form item. This is probably the trickiest of your options, as you will need to use a negative lookahead or something similar to get the regex correct.
2) Have the validator call one or more functions that you write to handle your special cases. I don't know if validationEngine allows you to pass parameters to the function--the documentation says nothing about that--so I'd guess it doesn't. This may mean that you will need to either write a separate function for each default value or else use a global variable to indicate the default value you are checking for. A function for your Uname field in your code snippet might look like this:
function checkUname(field, rules, i, options){
if (field.val() == "User Name") {
return "You must type in your username.";
}
Once that function is defined, you can use something like this to use it:
<input type="text" class="form validate[required,funcCall[checkUname]]" id="Uname" name="Uname" value="User Name" onfocus="if(this.value=='User Name')this.value='';" onblur="if(this.value=='')this.value='User Name';" />
3) You can write a single JavaScript function that goes through each field in your form and, if it finds the default value, changes it to an empty string. Then attach that function to the onsubmit event in your form. This may be the easiest option, but it depends on your function running before the validationEngine code. If that's not the case, then it won't work.
Here is a good example
How do you validate optional fields with default value?
Otherwise see the question I posted as identical question with the possible change
jQuery.validator.addMethod("defaultInvalid", function(value, element) {
if (element.value == element.defaultValue) return false;
}
instead of the switch/case
<input type="text" id="Uname" name="Uname" value="User Name" onfocus="if(this.value==this.defaultValue) this.value=''"
onblur="if(this.value=='') this.value=this.defaultValue" />
You should set the placeholder value using the HTML5 placeholder attribute instead of JavaScript.

How can I find a space character in an <input> using CSS3 selectors?

My way: code
<form>
<input type="text" value="">
<input type="submit" value="submit"> type a space and press Submit
</form>
$('form').submit(function(){
if($('input').val() == ' ') {
alert($('input').val().length);
}
return false;
});
But I'd like to solve this problem using CSS3 selectors like $('input[value*=" "]')
If you are asking to use CSS3 selector through jquery then $(':input[value*=" "]') should do it.
example: http://www.jsfiddle.net/gaby/cruRd/
If you want to create an actual CSS3 rule in your stylesheet then input[value*=' ']{..} will work, but only for values in the actual attribute (in the source code) and not the value as modified inside the browser..
example: http://www.jsfiddle.net/gaby/VzE9T/
As far as I know, you cannot manipulate data with CSS; it's a formatting language. You don't have variables or functions which help you find something in a string. Use JS instead.

Javascript Array in Class = How to make it valid

I am using this jQuery validation library on my website. It requires me to put the validation rules in the class part of the input tag. ie <input class="validate[required,custom[onlyLetter],length[0,100]]" name="firstname" type="text" />
Now this causes me to end up with code in mine that looks similar such as:
<input type="text"
id="charfname"
name="charfname"
value=""
style="width: 300px;"
class="validate[required,length[3,20],custom[noSpecialCaracters]]" />
Which as you see has a [ and ] in the class name. So when I run the page through a validator I get the error:
character "[" is not allowed in the value of attribute "class"
How do I fix this to make it valid but still have the library work?
Thanks
Use some other method for initialization or use another script? Use an alternate attribute and a custom DTD for example. Or throw away the attribute based init system and use something else. Either way you have to modify the plugin's code. You cannot use "[" and "]" characters in a class name and any other combination implying them, period.

Categories

Resources